SemaExpr.cpp 690 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838
  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 "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/EvaluatedExprVisitor.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/ExprOpenMP.h"
  25. #include "clang/AST/RecursiveASTVisitor.h"
  26. #include "clang/AST/TypeLoc.h"
  27. #include "clang/Basic/FixedPoint.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/LiteralSupport.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/AnalysisBasedWarnings.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Designator.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/Overload.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/Scope.h"
  42. #include "clang/Sema/ScopeInfo.h"
  43. #include "clang/Sema/SemaFixItUtils.h"
  44. #include "clang/Sema/SemaInternal.h"
  45. #include "clang/Sema/Template.h"
  46. #include "llvm/Support/ConvertUTF.h"
  47. using namespace clang;
  48. using namespace sema;
  49. /// Determine whether the use of this declaration is valid, without
  50. /// emitting diagnostics.
  51. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  52. // See if this is an auto-typed variable whose initializer we are parsing.
  53. if (ParsingInitForAutoVars.count(D))
  54. return false;
  55. // See if this is a deleted function.
  56. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  57. if (FD->isDeleted())
  58. return false;
  59. // If the function has a deduced return type, and we can't deduce it,
  60. // then we can't use it either.
  61. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  62. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  63. return false;
  64. // See if this is an aligned allocation/deallocation function that is
  65. // unavailable.
  66. if (TreatUnavailableAsInvalid &&
  67. isUnavailableAlignedAllocationFunction(*FD))
  68. return false;
  69. }
  70. // See if this function is unavailable.
  71. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  72. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  73. return false;
  74. return true;
  75. }
  76. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  77. // Warn if this is used but marked unused.
  78. if (const auto *A = D->getAttr<UnusedAttr>()) {
  79. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  80. // should diagnose them.
  81. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  82. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  83. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  84. if (DC && !DC->hasAttr<UnusedAttr>())
  85. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  86. }
  87. }
  88. }
  89. /// Emit a note explaining that this function is deleted.
  90. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  91. assert(Decl->isDeleted());
  92. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  93. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  94. // If the method was explicitly defaulted, point at that declaration.
  95. if (!Method->isImplicit())
  96. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  97. // Try to diagnose why this special member function was implicitly
  98. // deleted. This might fail, if that reason no longer applies.
  99. CXXSpecialMember CSM = getSpecialMember(Method);
  100. if (CSM != CXXInvalid)
  101. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  102. return;
  103. }
  104. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  105. if (Ctor && Ctor->isInheritingConstructor())
  106. return NoteDeletedInheritingConstructor(Ctor);
  107. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  108. << Decl << 1;
  109. }
  110. /// Determine whether a FunctionDecl was ever declared with an
  111. /// explicit storage class.
  112. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  113. for (auto I : D->redecls()) {
  114. if (I->getStorageClass() != SC_None)
  115. return true;
  116. }
  117. return false;
  118. }
  119. /// Check whether we're in an extern inline function and referring to a
  120. /// variable or function with internal linkage (C11 6.7.4p3).
  121. ///
  122. /// This is only a warning because we used to silently accept this code, but
  123. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  124. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  125. /// and so while there may still be user mistakes, most of the time we can't
  126. /// prove that there are errors.
  127. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  128. const NamedDecl *D,
  129. SourceLocation Loc) {
  130. // This is disabled under C++; there are too many ways for this to fire in
  131. // contexts where the warning is a false positive, or where it is technically
  132. // correct but benign.
  133. if (S.getLangOpts().CPlusPlus)
  134. return;
  135. // Check if this is an inlined function or method.
  136. FunctionDecl *Current = S.getCurFunctionDecl();
  137. if (!Current)
  138. return;
  139. if (!Current->isInlined())
  140. return;
  141. if (!Current->isExternallyVisible())
  142. return;
  143. // Check if the decl has internal linkage.
  144. if (D->getFormalLinkage() != InternalLinkage)
  145. return;
  146. // Downgrade from ExtWarn to Extension if
  147. // (1) the supposedly external inline function is in the main file,
  148. // and probably won't be included anywhere else.
  149. // (2) the thing we're referencing is a pure function.
  150. // (3) the thing we're referencing is another inline function.
  151. // This last can give us false negatives, but it's better than warning on
  152. // wrappers for simple C library functions.
  153. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  154. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  155. if (!DowngradeWarning && UsedFn)
  156. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  157. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  158. : diag::ext_internal_in_extern_inline)
  159. << /*IsVar=*/!UsedFn << D;
  160. S.MaybeSuggestAddingStaticToDecl(Current);
  161. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  162. << D;
  163. }
  164. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  165. const FunctionDecl *First = Cur->getFirstDecl();
  166. // Suggest "static" on the function, if possible.
  167. if (!hasAnyExplicitStorageClass(First)) {
  168. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  169. Diag(DeclBegin, diag::note_convert_inline_to_static)
  170. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  171. }
  172. }
  173. /// Determine whether the use of this declaration is valid, and
  174. /// emit any corresponding diagnostics.
  175. ///
  176. /// This routine diagnoses various problems with referencing
  177. /// declarations that can occur when using a declaration. For example,
  178. /// it might warn if a deprecated or unavailable declaration is being
  179. /// used, or produce an error (and return true) if a C++0x deleted
  180. /// function is being used.
  181. ///
  182. /// \returns true if there was an error (this declaration cannot be
  183. /// referenced), false otherwise.
  184. ///
  185. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
  186. const ObjCInterfaceDecl *UnknownObjCClass,
  187. bool ObjCPropertyAccess,
  188. bool AvoidPartialAvailabilityChecks,
  189. ObjCInterfaceDecl *ClassReceiver) {
  190. SourceLocation Loc = Locs.front();
  191. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  192. // If there were any diagnostics suppressed by template argument deduction,
  193. // emit them now.
  194. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  195. if (Pos != SuppressedDiagnostics.end()) {
  196. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  197. Diag(Suppressed.first, Suppressed.second);
  198. // Clear out the list of suppressed diagnostics, so that we don't emit
  199. // them again for this specialization. However, we don't obsolete this
  200. // entry from the table, because we want to avoid ever emitting these
  201. // diagnostics again.
  202. Pos->second.clear();
  203. }
  204. // C++ [basic.start.main]p3:
  205. // The function 'main' shall not be used within a program.
  206. if (cast<FunctionDecl>(D)->isMain())
  207. Diag(Loc, diag::ext_main_used);
  208. diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
  209. }
  210. // See if this is an auto-typed variable whose initializer we are parsing.
  211. if (ParsingInitForAutoVars.count(D)) {
  212. if (isa<BindingDecl>(D)) {
  213. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  214. << D->getDeclName();
  215. } else {
  216. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  217. << D->getDeclName() << cast<VarDecl>(D)->getType();
  218. }
  219. return true;
  220. }
  221. // See if this is a deleted function.
  222. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  223. if (FD->isDeleted()) {
  224. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  225. if (Ctor && Ctor->isInheritingConstructor())
  226. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  227. << Ctor->getParent()
  228. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  229. else
  230. Diag(Loc, diag::err_deleted_function_use);
  231. NoteDeletedFunction(FD);
  232. return true;
  233. }
  234. // If the function has a deduced return type, and we can't deduce it,
  235. // then we can't use it either.
  236. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  237. DeduceReturnType(FD, Loc))
  238. return true;
  239. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  240. return true;
  241. }
  242. if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  243. // Lambdas are only default-constructible or assignable in C++2a onwards.
  244. if (MD->getParent()->isLambda() &&
  245. ((isa<CXXConstructorDecl>(MD) &&
  246. cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
  247. MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
  248. Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
  249. << !isa<CXXConstructorDecl>(MD);
  250. }
  251. }
  252. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  253. const ObjCPropertyDecl * {
  254. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  255. return MD->findPropertyDecl();
  256. return nullptr;
  257. };
  258. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  259. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  260. return true;
  261. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  262. return true;
  263. }
  264. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  265. // Only the variables omp_in and omp_out are allowed in the combiner.
  266. // Only the variables omp_priv and omp_orig are allowed in the
  267. // initializer-clause.
  268. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  269. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  270. isa<VarDecl>(D)) {
  271. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  272. << getCurFunction()->HasOMPDeclareReductionCombiner;
  273. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  274. return true;
  275. }
  276. // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
  277. // List-items in map clauses on this construct may only refer to the declared
  278. // variable var and entities that could be referenced by a procedure defined
  279. // at the same location
  280. auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
  281. if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
  282. isa<VarDecl>(D)) {
  283. Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
  284. << DMD->getVarName().getAsString();
  285. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  286. return true;
  287. }
  288. DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
  289. AvoidPartialAvailabilityChecks, ClassReceiver);
  290. DiagnoseUnusedOfDecl(*this, D, Loc);
  291. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  292. return false;
  293. }
  294. /// DiagnoseSentinelCalls - This routine checks whether a call or
  295. /// message-send is to a declaration with the sentinel attribute, and
  296. /// if so, it checks that the requirements of the sentinel are
  297. /// satisfied.
  298. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  299. ArrayRef<Expr *> Args) {
  300. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  301. if (!attr)
  302. return;
  303. // The number of formal parameters of the declaration.
  304. unsigned numFormalParams;
  305. // The kind of declaration. This is also an index into a %select in
  306. // the diagnostic.
  307. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  308. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  309. numFormalParams = MD->param_size();
  310. calleeType = CT_Method;
  311. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  312. numFormalParams = FD->param_size();
  313. calleeType = CT_Function;
  314. } else if (isa<VarDecl>(D)) {
  315. QualType type = cast<ValueDecl>(D)->getType();
  316. const FunctionType *fn = nullptr;
  317. if (const PointerType *ptr = type->getAs<PointerType>()) {
  318. fn = ptr->getPointeeType()->getAs<FunctionType>();
  319. if (!fn) return;
  320. calleeType = CT_Function;
  321. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  322. fn = ptr->getPointeeType()->castAs<FunctionType>();
  323. calleeType = CT_Block;
  324. } else {
  325. return;
  326. }
  327. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  328. numFormalParams = proto->getNumParams();
  329. } else {
  330. numFormalParams = 0;
  331. }
  332. } else {
  333. return;
  334. }
  335. // "nullPos" is the number of formal parameters at the end which
  336. // effectively count as part of the variadic arguments. This is
  337. // useful if you would prefer to not have *any* formal parameters,
  338. // but the language forces you to have at least one.
  339. unsigned nullPos = attr->getNullPos();
  340. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  341. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  342. // The number of arguments which should follow the sentinel.
  343. unsigned numArgsAfterSentinel = attr->getSentinel();
  344. // If there aren't enough arguments for all the formal parameters,
  345. // the sentinel, and the args after the sentinel, complain.
  346. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  347. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  348. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  349. return;
  350. }
  351. // Otherwise, find the sentinel expression.
  352. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  353. if (!sentinelExpr) return;
  354. if (sentinelExpr->isValueDependent()) return;
  355. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  356. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  357. // or 'NULL' if those are actually defined in the context. Only use
  358. // 'nil' for ObjC methods, where it's much more likely that the
  359. // variadic arguments form a list of object pointers.
  360. SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
  361. std::string NullValue;
  362. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  363. NullValue = "nil";
  364. else if (getLangOpts().CPlusPlus11)
  365. NullValue = "nullptr";
  366. else if (PP.isMacroDefined("NULL"))
  367. NullValue = "NULL";
  368. else
  369. NullValue = "(void*) 0";
  370. if (MissingNilLoc.isInvalid())
  371. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  372. else
  373. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  374. << int(calleeType)
  375. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  376. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  377. }
  378. SourceRange Sema::getExprRange(Expr *E) const {
  379. return E ? E->getSourceRange() : SourceRange();
  380. }
  381. //===----------------------------------------------------------------------===//
  382. // Standard Promotions and Conversions
  383. //===----------------------------------------------------------------------===//
  384. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  385. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  386. // Handle any placeholder expressions which made it here.
  387. if (E->getType()->isPlaceholderType()) {
  388. ExprResult result = CheckPlaceholderExpr(E);
  389. if (result.isInvalid()) return ExprError();
  390. E = result.get();
  391. }
  392. QualType Ty = E->getType();
  393. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  394. if (Ty->isFunctionType()) {
  395. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  396. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  397. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  398. return ExprError();
  399. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  400. CK_FunctionToPointerDecay).get();
  401. } else if (Ty->isArrayType()) {
  402. // In C90 mode, arrays only promote to pointers if the array expression is
  403. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  404. // type 'array of type' is converted to an expression that has type 'pointer
  405. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  406. // that has type 'array of type' ...". The relevant change is "an lvalue"
  407. // (C90) to "an expression" (C99).
  408. //
  409. // C++ 4.2p1:
  410. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  411. // T" can be converted to an rvalue of type "pointer to T".
  412. //
  413. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  414. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  415. CK_ArrayToPointerDecay).get();
  416. }
  417. return E;
  418. }
  419. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  420. // Check to see if we are dereferencing a null pointer. If so,
  421. // and if not volatile-qualified, this is undefined behavior that the
  422. // optimizer will delete, so warn about it. People sometimes try to use this
  423. // to get a deterministic trap and are surprised by clang's behavior. This
  424. // only handles the pattern "*null", which is a very syntactic check.
  425. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  426. if (UO->getOpcode() == UO_Deref &&
  427. UO->getSubExpr()->IgnoreParenCasts()->
  428. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  429. !UO->getType().isVolatileQualified()) {
  430. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  431. S.PDiag(diag::warn_indirection_through_null)
  432. << UO->getSubExpr()->getSourceRange());
  433. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  434. S.PDiag(diag::note_indirection_through_null));
  435. }
  436. }
  437. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  438. SourceLocation AssignLoc,
  439. const Expr* RHS) {
  440. const ObjCIvarDecl *IV = OIRE->getDecl();
  441. if (!IV)
  442. return;
  443. DeclarationName MemberName = IV->getDeclName();
  444. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  445. if (!Member || !Member->isStr("isa"))
  446. return;
  447. const Expr *Base = OIRE->getBase();
  448. QualType BaseType = Base->getType();
  449. if (OIRE->isArrow())
  450. BaseType = BaseType->getPointeeType();
  451. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  452. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  453. ObjCInterfaceDecl *ClassDeclared = nullptr;
  454. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  455. if (!ClassDeclared->getSuperClass()
  456. && (*ClassDeclared->ivar_begin()) == IV) {
  457. if (RHS) {
  458. NamedDecl *ObjectSetClass =
  459. S.LookupSingleName(S.TUScope,
  460. &S.Context.Idents.get("object_setClass"),
  461. SourceLocation(), S.LookupOrdinaryName);
  462. if (ObjectSetClass) {
  463. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
  464. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
  465. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  466. "object_setClass(")
  467. << FixItHint::CreateReplacement(
  468. SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
  469. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  470. }
  471. else
  472. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  473. } else {
  474. NamedDecl *ObjectGetClass =
  475. S.LookupSingleName(S.TUScope,
  476. &S.Context.Idents.get("object_getClass"),
  477. SourceLocation(), S.LookupOrdinaryName);
  478. if (ObjectGetClass)
  479. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
  480. << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
  481. "object_getClass(")
  482. << FixItHint::CreateReplacement(
  483. SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
  484. else
  485. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  486. }
  487. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  488. }
  489. }
  490. }
  491. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  492. // Handle any placeholder expressions which made it here.
  493. if (E->getType()->isPlaceholderType()) {
  494. ExprResult result = CheckPlaceholderExpr(E);
  495. if (result.isInvalid()) return ExprError();
  496. E = result.get();
  497. }
  498. // C++ [conv.lval]p1:
  499. // A glvalue of a non-function, non-array type T can be
  500. // converted to a prvalue.
  501. if (!E->isGLValue()) return E;
  502. QualType T = E->getType();
  503. assert(!T.isNull() && "r-value conversion on typeless expression?");
  504. // We don't want to throw lvalue-to-rvalue casts on top of
  505. // expressions of certain types in C++.
  506. if (getLangOpts().CPlusPlus &&
  507. (E->getType() == Context.OverloadTy ||
  508. T->isDependentType() ||
  509. T->isRecordType()))
  510. return E;
  511. // The C standard is actually really unclear on this point, and
  512. // DR106 tells us what the result should be but not why. It's
  513. // generally best to say that void types just doesn't undergo
  514. // lvalue-to-rvalue at all. Note that expressions of unqualified
  515. // 'void' type are never l-values, but qualified void can be.
  516. if (T->isVoidType())
  517. return E;
  518. // OpenCL usually rejects direct accesses to values of 'half' type.
  519. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  520. T->isHalfType()) {
  521. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  522. << 0 << T;
  523. return ExprError();
  524. }
  525. CheckForNullPointerDereference(*this, E);
  526. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  527. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  528. &Context.Idents.get("object_getClass"),
  529. SourceLocation(), LookupOrdinaryName);
  530. if (ObjectGetClass)
  531. Diag(E->getExprLoc(), diag::warn_objc_isa_use)
  532. << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
  533. << FixItHint::CreateReplacement(
  534. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  535. else
  536. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  537. }
  538. else if (const ObjCIvarRefExpr *OIRE =
  539. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  540. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  541. // C++ [conv.lval]p1:
  542. // [...] If T is a non-class type, the type of the prvalue is the
  543. // cv-unqualified version of T. Otherwise, the type of the
  544. // rvalue is T.
  545. //
  546. // C99 6.3.2.1p2:
  547. // If the lvalue has qualified type, the value has the unqualified
  548. // version of the type of the lvalue; otherwise, the value has the
  549. // type of the lvalue.
  550. if (T.hasQualifiers())
  551. T = T.getUnqualifiedType();
  552. // Under the MS ABI, lock down the inheritance model now.
  553. if (T->isMemberPointerType() &&
  554. Context.getTargetInfo().getCXXABI().isMicrosoft())
  555. (void)isCompleteType(E->getExprLoc(), T);
  556. ExprResult Res = CheckLValueToRValueConversionOperand(E);
  557. if (Res.isInvalid())
  558. return Res;
  559. E = Res.get();
  560. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  561. // balance that.
  562. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  563. Cleanup.setExprNeedsCleanups(true);
  564. // C++ [conv.lval]p3:
  565. // If T is cv std::nullptr_t, the result is a null pointer constant.
  566. CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
  567. Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
  568. // C11 6.3.2.1p2:
  569. // ... if the lvalue has atomic type, the value has the non-atomic version
  570. // of the type of the lvalue ...
  571. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  572. T = Atomic->getValueType().getUnqualifiedType();
  573. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  574. nullptr, VK_RValue);
  575. }
  576. return Res;
  577. }
  578. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  579. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  580. if (Res.isInvalid())
  581. return ExprError();
  582. Res = DefaultLvalueConversion(Res.get());
  583. if (Res.isInvalid())
  584. return ExprError();
  585. return Res;
  586. }
  587. /// CallExprUnaryConversions - a special case of an unary conversion
  588. /// performed on a function designator of a call expression.
  589. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  590. QualType Ty = E->getType();
  591. ExprResult Res = E;
  592. // Only do implicit cast for a function type, but not for a pointer
  593. // to function type.
  594. if (Ty->isFunctionType()) {
  595. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  596. CK_FunctionToPointerDecay).get();
  597. if (Res.isInvalid())
  598. return ExprError();
  599. }
  600. Res = DefaultLvalueConversion(Res.get());
  601. if (Res.isInvalid())
  602. return ExprError();
  603. return Res.get();
  604. }
  605. /// UsualUnaryConversions - Performs various conversions that are common to most
  606. /// operators (C99 6.3). The conversions of array and function types are
  607. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  608. /// apply if the array is an argument to the sizeof or address (&) operators.
  609. /// In these instances, this routine should *not* be called.
  610. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  611. // First, convert to an r-value.
  612. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  613. if (Res.isInvalid())
  614. return ExprError();
  615. E = Res.get();
  616. QualType Ty = E->getType();
  617. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  618. // Half FP have to be promoted to float unless it is natively supported
  619. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  620. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  621. // Try to perform integral promotions if the object has a theoretically
  622. // promotable type.
  623. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  624. // C99 6.3.1.1p2:
  625. //
  626. // The following may be used in an expression wherever an int or
  627. // unsigned int may be used:
  628. // - an object or expression with an integer type whose integer
  629. // conversion rank is less than or equal to the rank of int
  630. // and unsigned int.
  631. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  632. //
  633. // If an int can represent all values of the original type, the
  634. // value is converted to an int; otherwise, it is converted to an
  635. // unsigned int. These are called the integer promotions. All
  636. // other types are unchanged by the integer promotions.
  637. QualType PTy = Context.isPromotableBitField(E);
  638. if (!PTy.isNull()) {
  639. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  640. return E;
  641. }
  642. if (Ty->isPromotableIntegerType()) {
  643. QualType PT = Context.getPromotedIntegerType(Ty);
  644. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  645. return E;
  646. }
  647. }
  648. return E;
  649. }
  650. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  651. /// do not have a prototype. Arguments that have type float or __fp16
  652. /// are promoted to double. All other argument types are converted by
  653. /// UsualUnaryConversions().
  654. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  655. QualType Ty = E->getType();
  656. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  657. ExprResult Res = UsualUnaryConversions(E);
  658. if (Res.isInvalid())
  659. return ExprError();
  660. E = Res.get();
  661. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  662. // promote to double.
  663. // Note that default argument promotion applies only to float (and
  664. // half/fp16); it does not apply to _Float16.
  665. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  666. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  667. BTy->getKind() == BuiltinType::Float)) {
  668. if (getLangOpts().OpenCL &&
  669. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  670. if (BTy->getKind() == BuiltinType::Half) {
  671. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  672. }
  673. } else {
  674. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  675. }
  676. }
  677. // C++ performs lvalue-to-rvalue conversion as a default argument
  678. // promotion, even on class types, but note:
  679. // C++11 [conv.lval]p2:
  680. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  681. // operand or a subexpression thereof the value contained in the
  682. // referenced object is not accessed. Otherwise, if the glvalue
  683. // has a class type, the conversion copy-initializes a temporary
  684. // of type T from the glvalue and the result of the conversion
  685. // is a prvalue for the temporary.
  686. // FIXME: add some way to gate this entire thing for correctness in
  687. // potentially potentially evaluated contexts.
  688. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  689. ExprResult Temp = PerformCopyInitialization(
  690. InitializedEntity::InitializeTemporary(E->getType()),
  691. E->getExprLoc(), E);
  692. if (Temp.isInvalid())
  693. return ExprError();
  694. E = Temp.get();
  695. }
  696. return E;
  697. }
  698. /// Determine the degree of POD-ness for an expression.
  699. /// Incomplete types are considered POD, since this check can be performed
  700. /// when we're in an unevaluated context.
  701. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  702. if (Ty->isIncompleteType()) {
  703. // C++11 [expr.call]p7:
  704. // After these conversions, if the argument does not have arithmetic,
  705. // enumeration, pointer, pointer to member, or class type, the program
  706. // is ill-formed.
  707. //
  708. // Since we've already performed array-to-pointer and function-to-pointer
  709. // decay, the only such type in C++ is cv void. This also handles
  710. // initializer lists as variadic arguments.
  711. if (Ty->isVoidType())
  712. return VAK_Invalid;
  713. if (Ty->isObjCObjectType())
  714. return VAK_Invalid;
  715. return VAK_Valid;
  716. }
  717. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  718. return VAK_Invalid;
  719. if (Ty.isCXX98PODType(Context))
  720. return VAK_Valid;
  721. // C++11 [expr.call]p7:
  722. // Passing a potentially-evaluated argument of class type (Clause 9)
  723. // having a non-trivial copy constructor, a non-trivial move constructor,
  724. // or a non-trivial destructor, with no corresponding parameter,
  725. // is conditionally-supported with implementation-defined semantics.
  726. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  727. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  728. if (!Record->hasNonTrivialCopyConstructor() &&
  729. !Record->hasNonTrivialMoveConstructor() &&
  730. !Record->hasNonTrivialDestructor())
  731. return VAK_ValidInCXX11;
  732. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  733. return VAK_Valid;
  734. if (Ty->isObjCObjectType())
  735. return VAK_Invalid;
  736. if (getLangOpts().MSVCCompat)
  737. return VAK_MSVCUndefined;
  738. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  739. // permitted to reject them. We should consider doing so.
  740. return VAK_Undefined;
  741. }
  742. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  743. // Don't allow one to pass an Objective-C interface to a vararg.
  744. const QualType &Ty = E->getType();
  745. VarArgKind VAK = isValidVarArgType(Ty);
  746. // Complain about passing non-POD types through varargs.
  747. switch (VAK) {
  748. case VAK_ValidInCXX11:
  749. DiagRuntimeBehavior(
  750. E->getBeginLoc(), nullptr,
  751. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
  752. LLVM_FALLTHROUGH;
  753. case VAK_Valid:
  754. if (Ty->isRecordType()) {
  755. // This is unlikely to be what the user intended. If the class has a
  756. // 'c_str' member function, the user probably meant to call that.
  757. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  758. PDiag(diag::warn_pass_class_arg_to_vararg)
  759. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  760. }
  761. break;
  762. case VAK_Undefined:
  763. case VAK_MSVCUndefined:
  764. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  765. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  766. << getLangOpts().CPlusPlus11 << Ty << CT);
  767. break;
  768. case VAK_Invalid:
  769. if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
  770. Diag(E->getBeginLoc(),
  771. diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
  772. << Ty << CT;
  773. else if (Ty->isObjCObjectType())
  774. DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
  775. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  776. << Ty << CT);
  777. else
  778. Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
  779. << isa<InitListExpr>(E) << Ty << CT;
  780. break;
  781. }
  782. }
  783. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  784. /// will create a trap if the resulting type is not a POD type.
  785. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  786. FunctionDecl *FDecl) {
  787. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  788. // Strip the unbridged-cast placeholder expression off, if applicable.
  789. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  790. (CT == VariadicMethod ||
  791. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  792. E = stripARCUnbridgedCast(E);
  793. // Otherwise, do normal placeholder checking.
  794. } else {
  795. ExprResult ExprRes = CheckPlaceholderExpr(E);
  796. if (ExprRes.isInvalid())
  797. return ExprError();
  798. E = ExprRes.get();
  799. }
  800. }
  801. ExprResult ExprRes = DefaultArgumentPromotion(E);
  802. if (ExprRes.isInvalid())
  803. return ExprError();
  804. E = ExprRes.get();
  805. // Diagnostics regarding non-POD argument types are
  806. // emitted along with format string checking in Sema::CheckFunctionCall().
  807. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  808. // Turn this into a trap.
  809. CXXScopeSpec SS;
  810. SourceLocation TemplateKWLoc;
  811. UnqualifiedId Name;
  812. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  813. E->getBeginLoc());
  814. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
  815. /*HasTrailingLParen=*/true,
  816. /*IsAddressOfOperand=*/false);
  817. if (TrapFn.isInvalid())
  818. return ExprError();
  819. ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
  820. None, E->getEndLoc());
  821. if (Call.isInvalid())
  822. return ExprError();
  823. ExprResult Comma =
  824. ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
  825. if (Comma.isInvalid())
  826. return ExprError();
  827. return Comma.get();
  828. }
  829. if (!getLangOpts().CPlusPlus &&
  830. RequireCompleteType(E->getExprLoc(), E->getType(),
  831. diag::err_call_incomplete_argument))
  832. return ExprError();
  833. return E;
  834. }
  835. /// Converts an integer to complex float type. Helper function of
  836. /// UsualArithmeticConversions()
  837. ///
  838. /// \return false if the integer expression is an integer type and is
  839. /// successfully converted to the complex type.
  840. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  841. ExprResult &ComplexExpr,
  842. QualType IntTy,
  843. QualType ComplexTy,
  844. bool SkipCast) {
  845. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  846. if (SkipCast) return false;
  847. if (IntTy->isIntegerType()) {
  848. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  849. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  850. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  851. CK_FloatingRealToComplex);
  852. } else {
  853. assert(IntTy->isComplexIntegerType());
  854. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  855. CK_IntegralComplexToFloatingComplex);
  856. }
  857. return false;
  858. }
  859. /// Handle arithmetic conversion with complex types. Helper function of
  860. /// UsualArithmeticConversions()
  861. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  862. ExprResult &RHS, QualType LHSType,
  863. QualType RHSType,
  864. bool IsCompAssign) {
  865. // if we have an integer operand, the result is the complex type.
  866. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  867. /*skipCast*/false))
  868. return LHSType;
  869. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  870. /*skipCast*/IsCompAssign))
  871. return RHSType;
  872. // This handles complex/complex, complex/float, or float/complex.
  873. // When both operands are complex, the shorter operand is converted to the
  874. // type of the longer, and that is the type of the result. This corresponds
  875. // to what is done when combining two real floating-point operands.
  876. // The fun begins when size promotion occur across type domains.
  877. // From H&S 6.3.4: When one operand is complex and the other is a real
  878. // floating-point type, the less precise type is converted, within it's
  879. // real or complex domain, to the precision of the other type. For example,
  880. // when combining a "long double" with a "double _Complex", the
  881. // "double _Complex" is promoted to "long double _Complex".
  882. // Compute the rank of the two types, regardless of whether they are complex.
  883. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  884. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  885. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  886. QualType LHSElementType =
  887. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  888. QualType RHSElementType =
  889. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  890. QualType ResultType = S.Context.getComplexType(LHSElementType);
  891. if (Order < 0) {
  892. // Promote the precision of the LHS if not an assignment.
  893. ResultType = S.Context.getComplexType(RHSElementType);
  894. if (!IsCompAssign) {
  895. if (LHSComplexType)
  896. LHS =
  897. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  898. else
  899. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  900. }
  901. } else if (Order > 0) {
  902. // Promote the precision of the RHS.
  903. if (RHSComplexType)
  904. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  905. else
  906. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  907. }
  908. return ResultType;
  909. }
  910. /// Handle arithmetic conversion from integer to float. Helper function
  911. /// of UsualArithmeticConversions()
  912. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  913. ExprResult &IntExpr,
  914. QualType FloatTy, QualType IntTy,
  915. bool ConvertFloat, bool ConvertInt) {
  916. if (IntTy->isIntegerType()) {
  917. if (ConvertInt)
  918. // Convert intExpr to the lhs floating point type.
  919. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  920. CK_IntegralToFloating);
  921. return FloatTy;
  922. }
  923. // Convert both sides to the appropriate complex float.
  924. assert(IntTy->isComplexIntegerType());
  925. QualType result = S.Context.getComplexType(FloatTy);
  926. // _Complex int -> _Complex float
  927. if (ConvertInt)
  928. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  929. CK_IntegralComplexToFloatingComplex);
  930. // float -> _Complex float
  931. if (ConvertFloat)
  932. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  933. CK_FloatingRealToComplex);
  934. return result;
  935. }
  936. /// Handle arithmethic conversion with floating point types. Helper
  937. /// function of UsualArithmeticConversions()
  938. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  939. ExprResult &RHS, QualType LHSType,
  940. QualType RHSType, bool IsCompAssign) {
  941. bool LHSFloat = LHSType->isRealFloatingType();
  942. bool RHSFloat = RHSType->isRealFloatingType();
  943. // If we have two real floating types, convert the smaller operand
  944. // to the bigger result.
  945. if (LHSFloat && RHSFloat) {
  946. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  947. if (order > 0) {
  948. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  949. return LHSType;
  950. }
  951. assert(order < 0 && "illegal float comparison");
  952. if (!IsCompAssign)
  953. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  954. return RHSType;
  955. }
  956. if (LHSFloat) {
  957. // Half FP has to be promoted to float unless it is natively supported
  958. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  959. LHSType = S.Context.FloatTy;
  960. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  961. /*ConvertFloat=*/!IsCompAssign,
  962. /*ConvertInt=*/ true);
  963. }
  964. assert(RHSFloat);
  965. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  966. /*convertInt=*/ true,
  967. /*convertFloat=*/!IsCompAssign);
  968. }
  969. /// Diagnose attempts to convert between __float128 and long double if
  970. /// there is no support for such conversion. Helper function of
  971. /// UsualArithmeticConversions().
  972. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  973. QualType RHSType) {
  974. /* No issue converting if at least one of the types is not a floating point
  975. type or the two types have the same rank.
  976. */
  977. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  978. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  979. return false;
  980. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  981. "The remaining types must be floating point types.");
  982. auto *LHSComplex = LHSType->getAs<ComplexType>();
  983. auto *RHSComplex = RHSType->getAs<ComplexType>();
  984. QualType LHSElemType = LHSComplex ?
  985. LHSComplex->getElementType() : LHSType;
  986. QualType RHSElemType = RHSComplex ?
  987. RHSComplex->getElementType() : RHSType;
  988. // No issue if the two types have the same representation
  989. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  990. &S.Context.getFloatTypeSemantics(RHSElemType))
  991. return false;
  992. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  993. RHSElemType == S.Context.LongDoubleTy);
  994. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  995. RHSElemType == S.Context.Float128Ty);
  996. // We've handled the situation where __float128 and long double have the same
  997. // representation. We allow all conversions for all possible long double types
  998. // except PPC's double double.
  999. return Float128AndLongDouble &&
  1000. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
  1001. &llvm::APFloat::PPCDoubleDouble());
  1002. }
  1003. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  1004. namespace {
  1005. /// These helper callbacks are placed in an anonymous namespace to
  1006. /// permit their use as function template parameters.
  1007. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  1008. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  1009. }
  1010. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  1011. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  1012. CK_IntegralComplexCast);
  1013. }
  1014. }
  1015. /// Handle integer arithmetic conversions. Helper function of
  1016. /// UsualArithmeticConversions()
  1017. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  1018. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  1019. ExprResult &RHS, QualType LHSType,
  1020. QualType RHSType, bool IsCompAssign) {
  1021. // The rules for this case are in C99 6.3.1.8
  1022. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  1023. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  1024. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  1025. if (LHSSigned == RHSSigned) {
  1026. // Same signedness; use the higher-ranked type
  1027. if (order >= 0) {
  1028. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1029. return LHSType;
  1030. } else if (!IsCompAssign)
  1031. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1032. return RHSType;
  1033. } else if (order != (LHSSigned ? 1 : -1)) {
  1034. // The unsigned type has greater than or equal rank to the
  1035. // signed type, so use the unsigned type
  1036. if (RHSSigned) {
  1037. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1038. return LHSType;
  1039. } else if (!IsCompAssign)
  1040. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1041. return RHSType;
  1042. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1043. // The two types are different widths; if we are here, that
  1044. // means the signed type is larger than the unsigned type, so
  1045. // use the signed type.
  1046. if (LHSSigned) {
  1047. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1048. return LHSType;
  1049. } else if (!IsCompAssign)
  1050. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1051. return RHSType;
  1052. } else {
  1053. // The signed type is higher-ranked than the unsigned type,
  1054. // but isn't actually any bigger (like unsigned int and long
  1055. // on most 32-bit systems). Use the unsigned type corresponding
  1056. // to the signed type.
  1057. QualType result =
  1058. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1059. RHS = (*doRHSCast)(S, RHS.get(), result);
  1060. if (!IsCompAssign)
  1061. LHS = (*doLHSCast)(S, LHS.get(), result);
  1062. return result;
  1063. }
  1064. }
  1065. /// Handle conversions with GCC complex int extension. Helper function
  1066. /// of UsualArithmeticConversions()
  1067. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1068. ExprResult &RHS, QualType LHSType,
  1069. QualType RHSType,
  1070. bool IsCompAssign) {
  1071. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1072. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1073. if (LHSComplexInt && RHSComplexInt) {
  1074. QualType LHSEltType = LHSComplexInt->getElementType();
  1075. QualType RHSEltType = RHSComplexInt->getElementType();
  1076. QualType ScalarType =
  1077. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1078. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1079. return S.Context.getComplexType(ScalarType);
  1080. }
  1081. if (LHSComplexInt) {
  1082. QualType LHSEltType = LHSComplexInt->getElementType();
  1083. QualType ScalarType =
  1084. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1085. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1086. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1087. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1088. CK_IntegralRealToComplex);
  1089. return ComplexType;
  1090. }
  1091. assert(RHSComplexInt);
  1092. QualType RHSEltType = RHSComplexInt->getElementType();
  1093. QualType ScalarType =
  1094. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1095. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1096. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1097. if (!IsCompAssign)
  1098. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1099. CK_IntegralRealToComplex);
  1100. return ComplexType;
  1101. }
  1102. /// Return the rank of a given fixed point or integer type. The value itself
  1103. /// doesn't matter, but the values must be increasing with proper increasing
  1104. /// rank as described in N1169 4.1.1.
  1105. static unsigned GetFixedPointRank(QualType Ty) {
  1106. const auto *BTy = Ty->getAs<BuiltinType>();
  1107. assert(BTy && "Expected a builtin type.");
  1108. switch (BTy->getKind()) {
  1109. case BuiltinType::ShortFract:
  1110. case BuiltinType::UShortFract:
  1111. case BuiltinType::SatShortFract:
  1112. case BuiltinType::SatUShortFract:
  1113. return 1;
  1114. case BuiltinType::Fract:
  1115. case BuiltinType::UFract:
  1116. case BuiltinType::SatFract:
  1117. case BuiltinType::SatUFract:
  1118. return 2;
  1119. case BuiltinType::LongFract:
  1120. case BuiltinType::ULongFract:
  1121. case BuiltinType::SatLongFract:
  1122. case BuiltinType::SatULongFract:
  1123. return 3;
  1124. case BuiltinType::ShortAccum:
  1125. case BuiltinType::UShortAccum:
  1126. case BuiltinType::SatShortAccum:
  1127. case BuiltinType::SatUShortAccum:
  1128. return 4;
  1129. case BuiltinType::Accum:
  1130. case BuiltinType::UAccum:
  1131. case BuiltinType::SatAccum:
  1132. case BuiltinType::SatUAccum:
  1133. return 5;
  1134. case BuiltinType::LongAccum:
  1135. case BuiltinType::ULongAccum:
  1136. case BuiltinType::SatLongAccum:
  1137. case BuiltinType::SatULongAccum:
  1138. return 6;
  1139. default:
  1140. if (BTy->isInteger())
  1141. return 0;
  1142. llvm_unreachable("Unexpected fixed point or integer type");
  1143. }
  1144. }
  1145. /// handleFixedPointConversion - Fixed point operations between fixed
  1146. /// point types and integers or other fixed point types do not fall under
  1147. /// usual arithmetic conversion since these conversions could result in loss
  1148. /// of precsision (N1169 4.1.4). These operations should be calculated with
  1149. /// the full precision of their result type (N1169 4.1.6.2.1).
  1150. static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
  1151. QualType RHSTy) {
  1152. assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
  1153. "Expected at least one of the operands to be a fixed point type");
  1154. assert((LHSTy->isFixedPointOrIntegerType() ||
  1155. RHSTy->isFixedPointOrIntegerType()) &&
  1156. "Special fixed point arithmetic operation conversions are only "
  1157. "applied to ints or other fixed point types");
  1158. // If one operand has signed fixed-point type and the other operand has
  1159. // unsigned fixed-point type, then the unsigned fixed-point operand is
  1160. // converted to its corresponding signed fixed-point type and the resulting
  1161. // type is the type of the converted operand.
  1162. if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
  1163. LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
  1164. else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
  1165. RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
  1166. // The result type is the type with the highest rank, whereby a fixed-point
  1167. // conversion rank is always greater than an integer conversion rank; if the
  1168. // type of either of the operands is a saturating fixedpoint type, the result
  1169. // type shall be the saturating fixed-point type corresponding to the type
  1170. // with the highest rank; the resulting value is converted (taking into
  1171. // account rounding and overflow) to the precision of the resulting type.
  1172. // Same ranks between signed and unsigned types are resolved earlier, so both
  1173. // types are either signed or both unsigned at this point.
  1174. unsigned LHSTyRank = GetFixedPointRank(LHSTy);
  1175. unsigned RHSTyRank = GetFixedPointRank(RHSTy);
  1176. QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
  1177. if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
  1178. ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
  1179. return ResultTy;
  1180. }
  1181. /// UsualArithmeticConversions - Performs various conversions that are common to
  1182. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1183. /// routine returns the first non-arithmetic type found. The client is
  1184. /// responsible for emitting appropriate error diagnostics.
  1185. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1186. bool IsCompAssign) {
  1187. if (!IsCompAssign) {
  1188. LHS = UsualUnaryConversions(LHS.get());
  1189. if (LHS.isInvalid())
  1190. return QualType();
  1191. }
  1192. RHS = UsualUnaryConversions(RHS.get());
  1193. if (RHS.isInvalid())
  1194. return QualType();
  1195. // For conversion purposes, we ignore any qualifiers.
  1196. // For example, "const float" and "float" are equivalent.
  1197. QualType LHSType =
  1198. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1199. QualType RHSType =
  1200. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1201. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1202. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1203. LHSType = AtomicLHS->getValueType();
  1204. // If both types are identical, no conversion is needed.
  1205. if (LHSType == RHSType)
  1206. return LHSType;
  1207. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1208. // The caller can deal with this (e.g. pointer + int).
  1209. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1210. return QualType();
  1211. // Apply unary and bitfield promotions to the LHS's type.
  1212. QualType LHSUnpromotedType = LHSType;
  1213. if (LHSType->isPromotableIntegerType())
  1214. LHSType = Context.getPromotedIntegerType(LHSType);
  1215. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1216. if (!LHSBitfieldPromoteTy.isNull())
  1217. LHSType = LHSBitfieldPromoteTy;
  1218. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1219. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1220. // If both types are identical, no conversion is needed.
  1221. if (LHSType == RHSType)
  1222. return LHSType;
  1223. // At this point, we have two different arithmetic types.
  1224. // Diagnose attempts to convert between __float128 and long double where
  1225. // such conversions currently can't be handled.
  1226. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1227. return QualType();
  1228. // Handle complex types first (C99 6.3.1.8p1).
  1229. if (LHSType->isComplexType() || RHSType->isComplexType())
  1230. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1231. IsCompAssign);
  1232. // Now handle "real" floating types (i.e. float, double, long double).
  1233. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1234. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1235. IsCompAssign);
  1236. // Handle GCC complex int extension.
  1237. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1238. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1239. IsCompAssign);
  1240. if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
  1241. return handleFixedPointConversion(*this, LHSType, RHSType);
  1242. // Finally, we have two differing integer types.
  1243. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1244. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1245. }
  1246. //===----------------------------------------------------------------------===//
  1247. // Semantic Analysis for various Expression Types
  1248. //===----------------------------------------------------------------------===//
  1249. ExprResult
  1250. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1251. SourceLocation DefaultLoc,
  1252. SourceLocation RParenLoc,
  1253. Expr *ControllingExpr,
  1254. ArrayRef<ParsedType> ArgTypes,
  1255. ArrayRef<Expr *> ArgExprs) {
  1256. unsigned NumAssocs = ArgTypes.size();
  1257. assert(NumAssocs == ArgExprs.size());
  1258. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1259. for (unsigned i = 0; i < NumAssocs; ++i) {
  1260. if (ArgTypes[i])
  1261. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1262. else
  1263. Types[i] = nullptr;
  1264. }
  1265. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1266. ControllingExpr,
  1267. llvm::makeArrayRef(Types, NumAssocs),
  1268. ArgExprs);
  1269. delete [] Types;
  1270. return ER;
  1271. }
  1272. ExprResult
  1273. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1274. SourceLocation DefaultLoc,
  1275. SourceLocation RParenLoc,
  1276. Expr *ControllingExpr,
  1277. ArrayRef<TypeSourceInfo *> Types,
  1278. ArrayRef<Expr *> Exprs) {
  1279. unsigned NumAssocs = Types.size();
  1280. assert(NumAssocs == Exprs.size());
  1281. // Decay and strip qualifiers for the controlling expression type, and handle
  1282. // placeholder type replacement. See committee discussion from WG14 DR423.
  1283. {
  1284. EnterExpressionEvaluationContext Unevaluated(
  1285. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1286. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1287. if (R.isInvalid())
  1288. return ExprError();
  1289. ControllingExpr = R.get();
  1290. }
  1291. // The controlling expression is an unevaluated operand, so side effects are
  1292. // likely unintended.
  1293. if (!inTemplateInstantiation() &&
  1294. ControllingExpr->HasSideEffects(Context, false))
  1295. Diag(ControllingExpr->getExprLoc(),
  1296. diag::warn_side_effects_unevaluated_context);
  1297. bool TypeErrorFound = false,
  1298. IsResultDependent = ControllingExpr->isTypeDependent(),
  1299. ContainsUnexpandedParameterPack
  1300. = ControllingExpr->containsUnexpandedParameterPack();
  1301. for (unsigned i = 0; i < NumAssocs; ++i) {
  1302. if (Exprs[i]->containsUnexpandedParameterPack())
  1303. ContainsUnexpandedParameterPack = true;
  1304. if (Types[i]) {
  1305. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1306. ContainsUnexpandedParameterPack = true;
  1307. if (Types[i]->getType()->isDependentType()) {
  1308. IsResultDependent = true;
  1309. } else {
  1310. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1311. // complete object type other than a variably modified type."
  1312. unsigned D = 0;
  1313. if (Types[i]->getType()->isIncompleteType())
  1314. D = diag::err_assoc_type_incomplete;
  1315. else if (!Types[i]->getType()->isObjectType())
  1316. D = diag::err_assoc_type_nonobject;
  1317. else if (Types[i]->getType()->isVariablyModifiedType())
  1318. D = diag::err_assoc_type_variably_modified;
  1319. if (D != 0) {
  1320. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1321. << Types[i]->getTypeLoc().getSourceRange()
  1322. << Types[i]->getType();
  1323. TypeErrorFound = true;
  1324. }
  1325. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1326. // selection shall specify compatible types."
  1327. for (unsigned j = i+1; j < NumAssocs; ++j)
  1328. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1329. Context.typesAreCompatible(Types[i]->getType(),
  1330. Types[j]->getType())) {
  1331. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1332. diag::err_assoc_compatible_types)
  1333. << Types[j]->getTypeLoc().getSourceRange()
  1334. << Types[j]->getType()
  1335. << Types[i]->getType();
  1336. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1337. diag::note_compat_assoc)
  1338. << Types[i]->getTypeLoc().getSourceRange()
  1339. << Types[i]->getType();
  1340. TypeErrorFound = true;
  1341. }
  1342. }
  1343. }
  1344. }
  1345. if (TypeErrorFound)
  1346. return ExprError();
  1347. // If we determined that the generic selection is result-dependent, don't
  1348. // try to compute the result expression.
  1349. if (IsResultDependent)
  1350. return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
  1351. Exprs, DefaultLoc, RParenLoc,
  1352. ContainsUnexpandedParameterPack);
  1353. SmallVector<unsigned, 1> CompatIndices;
  1354. unsigned DefaultIndex = -1U;
  1355. for (unsigned i = 0; i < NumAssocs; ++i) {
  1356. if (!Types[i])
  1357. DefaultIndex = i;
  1358. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1359. Types[i]->getType()))
  1360. CompatIndices.push_back(i);
  1361. }
  1362. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1363. // type compatible with at most one of the types named in its generic
  1364. // association list."
  1365. if (CompatIndices.size() > 1) {
  1366. // We strip parens here because the controlling expression is typically
  1367. // parenthesized in macro definitions.
  1368. ControllingExpr = ControllingExpr->IgnoreParens();
  1369. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
  1370. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1371. << (unsigned)CompatIndices.size();
  1372. for (unsigned I : CompatIndices) {
  1373. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1374. diag::note_compat_assoc)
  1375. << Types[I]->getTypeLoc().getSourceRange()
  1376. << Types[I]->getType();
  1377. }
  1378. return ExprError();
  1379. }
  1380. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1381. // its controlling expression shall have type compatible with exactly one of
  1382. // the types named in its generic association list."
  1383. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1384. // We strip parens here because the controlling expression is typically
  1385. // parenthesized in macro definitions.
  1386. ControllingExpr = ControllingExpr->IgnoreParens();
  1387. Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
  1388. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1389. return ExprError();
  1390. }
  1391. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1392. // type name that is compatible with the type of the controlling expression,
  1393. // then the result expression of the generic selection is the expression
  1394. // in that generic association. Otherwise, the result expression of the
  1395. // generic selection is the expression in the default generic association."
  1396. unsigned ResultIndex =
  1397. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1398. return GenericSelectionExpr::Create(
  1399. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1400. ContainsUnexpandedParameterPack, ResultIndex);
  1401. }
  1402. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1403. /// location of the token and the offset of the ud-suffix within it.
  1404. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1405. unsigned Offset) {
  1406. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1407. S.getLangOpts());
  1408. }
  1409. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1410. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1411. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1412. IdentifierInfo *UDSuffix,
  1413. SourceLocation UDSuffixLoc,
  1414. ArrayRef<Expr*> Args,
  1415. SourceLocation LitEndLoc) {
  1416. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1417. QualType ArgTy[2];
  1418. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1419. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1420. if (ArgTy[ArgIdx]->isArrayType())
  1421. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1422. }
  1423. DeclarationName OpName =
  1424. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1425. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1426. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1427. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1428. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1429. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1430. /*AllowStringTemplate*/ false,
  1431. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1432. return ExprError();
  1433. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1434. }
  1435. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1436. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1437. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1438. /// multiple tokens. However, the common case is that StringToks points to one
  1439. /// string.
  1440. ///
  1441. ExprResult
  1442. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1443. assert(!StringToks.empty() && "Must have at least one string!");
  1444. StringLiteralParser Literal(StringToks, PP);
  1445. if (Literal.hadError)
  1446. return ExprError();
  1447. SmallVector<SourceLocation, 4> StringTokLocs;
  1448. for (const Token &Tok : StringToks)
  1449. StringTokLocs.push_back(Tok.getLocation());
  1450. QualType CharTy = Context.CharTy;
  1451. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1452. if (Literal.isWide()) {
  1453. CharTy = Context.getWideCharType();
  1454. Kind = StringLiteral::Wide;
  1455. } else if (Literal.isUTF8()) {
  1456. if (getLangOpts().Char8)
  1457. CharTy = Context.Char8Ty;
  1458. Kind = StringLiteral::UTF8;
  1459. } else if (Literal.isUTF16()) {
  1460. CharTy = Context.Char16Ty;
  1461. Kind = StringLiteral::UTF16;
  1462. } else if (Literal.isUTF32()) {
  1463. CharTy = Context.Char32Ty;
  1464. Kind = StringLiteral::UTF32;
  1465. } else if (Literal.isPascal()) {
  1466. CharTy = Context.UnsignedCharTy;
  1467. }
  1468. // Warn on initializing an array of char from a u8 string literal; this
  1469. // becomes ill-formed in C++2a.
  1470. if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
  1471. !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
  1472. Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
  1473. // Create removals for all 'u8' prefixes in the string literal(s). This
  1474. // ensures C++2a compatibility (but may change the program behavior when
  1475. // built by non-Clang compilers for which the execution character set is
  1476. // not always UTF-8).
  1477. auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
  1478. SourceLocation RemovalDiagLoc;
  1479. for (const Token &Tok : StringToks) {
  1480. if (Tok.getKind() == tok::utf8_string_literal) {
  1481. if (RemovalDiagLoc.isInvalid())
  1482. RemovalDiagLoc = Tok.getLocation();
  1483. RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  1484. Tok.getLocation(),
  1485. Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
  1486. getSourceManager(), getLangOpts())));
  1487. }
  1488. }
  1489. Diag(RemovalDiagLoc, RemovalDiag);
  1490. }
  1491. QualType StrTy =
  1492. Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
  1493. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1494. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1495. Kind, Literal.Pascal, StrTy,
  1496. &StringTokLocs[0],
  1497. StringTokLocs.size());
  1498. if (Literal.getUDSuffix().empty())
  1499. return Lit;
  1500. // We're building a user-defined literal.
  1501. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1502. SourceLocation UDSuffixLoc =
  1503. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1504. Literal.getUDSuffixOffset());
  1505. // Make sure we're allowed user-defined literals here.
  1506. if (!UDLScope)
  1507. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1508. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1509. // operator "" X (str, len)
  1510. QualType SizeType = Context.getSizeType();
  1511. DeclarationName OpName =
  1512. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1513. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1514. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1515. QualType ArgTy[] = {
  1516. Context.getArrayDecayedType(StrTy), SizeType
  1517. };
  1518. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1519. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1520. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1521. /*AllowStringTemplate*/ true,
  1522. /*DiagnoseMissing*/ true)) {
  1523. case LOLR_Cooked: {
  1524. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1525. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1526. StringTokLocs[0]);
  1527. Expr *Args[] = { Lit, LenArg };
  1528. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1529. }
  1530. case LOLR_StringTemplate: {
  1531. TemplateArgumentListInfo ExplicitArgs;
  1532. unsigned CharBits = Context.getIntWidth(CharTy);
  1533. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1534. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1535. TemplateArgument TypeArg(CharTy);
  1536. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1537. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1538. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1539. Value = Lit->getCodeUnit(I);
  1540. TemplateArgument Arg(Context, Value, CharTy);
  1541. TemplateArgumentLocInfo ArgInfo;
  1542. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1543. }
  1544. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1545. &ExplicitArgs);
  1546. }
  1547. case LOLR_Raw:
  1548. case LOLR_Template:
  1549. case LOLR_ErrorNoDiagnostic:
  1550. llvm_unreachable("unexpected literal operator lookup result");
  1551. case LOLR_Error:
  1552. return ExprError();
  1553. }
  1554. llvm_unreachable("unexpected literal operator lookup result");
  1555. }
  1556. DeclRefExpr *
  1557. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1558. SourceLocation Loc,
  1559. const CXXScopeSpec *SS) {
  1560. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1561. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1562. }
  1563. DeclRefExpr *
  1564. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1565. const DeclarationNameInfo &NameInfo,
  1566. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1567. SourceLocation TemplateKWLoc,
  1568. const TemplateArgumentListInfo *TemplateArgs) {
  1569. NestedNameSpecifierLoc NNS =
  1570. SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
  1571. return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
  1572. TemplateArgs);
  1573. }
  1574. NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
  1575. // A declaration named in an unevaluated operand never constitutes an odr-use.
  1576. if (isUnevaluatedContext())
  1577. return NOUR_Unevaluated;
  1578. // C++2a [basic.def.odr]p4:
  1579. // A variable x whose name appears as a potentially-evaluated expression e
  1580. // is odr-used by e unless [...] x is a reference that is usable in
  1581. // constant expressions.
  1582. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1583. if (VD->getType()->isReferenceType() &&
  1584. !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
  1585. VD->isUsableInConstantExpressions(Context))
  1586. return NOUR_Constant;
  1587. }
  1588. // All remaining non-variable cases constitute an odr-use. For variables, we
  1589. // need to wait and see how the expression is used.
  1590. return NOUR_None;
  1591. }
  1592. /// BuildDeclRefExpr - Build an expression that references a
  1593. /// declaration that does not require a closure capture.
  1594. DeclRefExpr *
  1595. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1596. const DeclarationNameInfo &NameInfo,
  1597. NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
  1598. SourceLocation TemplateKWLoc,
  1599. const TemplateArgumentListInfo *TemplateArgs) {
  1600. bool RefersToCapturedVariable =
  1601. isa<VarDecl>(D) &&
  1602. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1603. DeclRefExpr *E = DeclRefExpr::Create(
  1604. Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
  1605. VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
  1606. MarkDeclRefReferenced(E);
  1607. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1608. Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
  1609. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
  1610. getCurFunction()->recordUseOfWeak(E);
  1611. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1612. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1613. FD = IFD->getAnonField();
  1614. if (FD) {
  1615. UnusedPrivateFields.remove(FD);
  1616. // Just in case we're building an illegal pointer-to-member.
  1617. if (FD->isBitField())
  1618. E->setObjectKind(OK_BitField);
  1619. }
  1620. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1621. // designates a bit-field.
  1622. if (auto *BD = dyn_cast<BindingDecl>(D))
  1623. if (auto *BE = BD->getBinding())
  1624. E->setObjectKind(BE->getObjectKind());
  1625. return E;
  1626. }
  1627. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1628. /// possibly a list of template arguments.
  1629. ///
  1630. /// If this produces template arguments, it is permitted to call
  1631. /// DecomposeTemplateName.
  1632. ///
  1633. /// This actually loses a lot of source location information for
  1634. /// non-standard name kinds; we should consider preserving that in
  1635. /// some way.
  1636. void
  1637. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1638. TemplateArgumentListInfo &Buffer,
  1639. DeclarationNameInfo &NameInfo,
  1640. const TemplateArgumentListInfo *&TemplateArgs) {
  1641. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
  1642. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1643. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1644. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1645. Id.TemplateId->NumArgs);
  1646. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1647. TemplateName TName = Id.TemplateId->Template.get();
  1648. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1649. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1650. TemplateArgs = &Buffer;
  1651. } else {
  1652. NameInfo = GetNameFromUnqualifiedId(Id);
  1653. TemplateArgs = nullptr;
  1654. }
  1655. }
  1656. static void emitEmptyLookupTypoDiagnostic(
  1657. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1658. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1659. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1660. DeclContext *Ctx =
  1661. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1662. if (!TC) {
  1663. // Emit a special diagnostic for failed member lookups.
  1664. // FIXME: computing the declaration context might fail here (?)
  1665. if (Ctx)
  1666. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1667. << SS.getRange();
  1668. else
  1669. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1670. return;
  1671. }
  1672. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1673. bool DroppedSpecifier =
  1674. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1675. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1676. ? diag::note_implicit_param_decl
  1677. : diag::note_previous_decl;
  1678. if (!Ctx)
  1679. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1680. SemaRef.PDiag(NoteID));
  1681. else
  1682. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1683. << Typo << Ctx << DroppedSpecifier
  1684. << SS.getRange(),
  1685. SemaRef.PDiag(NoteID));
  1686. }
  1687. /// Diagnose an empty lookup.
  1688. ///
  1689. /// \return false if new lookup candidates were found
  1690. bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1691. CorrectionCandidateCallback &CCC,
  1692. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1693. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1694. DeclarationName Name = R.getLookupName();
  1695. unsigned diagnostic = diag::err_undeclared_var_use;
  1696. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1697. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1698. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1699. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1700. diagnostic = diag::err_undeclared_use;
  1701. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1702. }
  1703. // If the original lookup was an unqualified lookup, fake an
  1704. // unqualified lookup. This is useful when (for example) the
  1705. // original lookup would not have found something because it was a
  1706. // dependent name.
  1707. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1708. while (DC) {
  1709. if (isa<CXXRecordDecl>(DC)) {
  1710. LookupQualifiedName(R, DC);
  1711. if (!R.empty()) {
  1712. // Don't give errors about ambiguities in this lookup.
  1713. R.suppressDiagnostics();
  1714. // During a default argument instantiation the CurContext points
  1715. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1716. // function parameter list, hence add an explicit check.
  1717. bool isDefaultArgument =
  1718. !CodeSynthesisContexts.empty() &&
  1719. CodeSynthesisContexts.back().Kind ==
  1720. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1721. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1722. bool isInstance = CurMethod &&
  1723. CurMethod->isInstance() &&
  1724. DC == CurMethod->getParent() && !isDefaultArgument;
  1725. // Give a code modification hint to insert 'this->'.
  1726. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1727. // Actually quite difficult!
  1728. if (getLangOpts().MSVCCompat)
  1729. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1730. if (isInstance) {
  1731. Diag(R.getNameLoc(), diagnostic) << Name
  1732. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1733. CheckCXXThisCapture(R.getNameLoc());
  1734. } else {
  1735. Diag(R.getNameLoc(), diagnostic) << Name;
  1736. }
  1737. // Do we really want to note all of these?
  1738. for (NamedDecl *D : R)
  1739. Diag(D->getLocation(), diag::note_dependent_var_use);
  1740. // Return true if we are inside a default argument instantiation
  1741. // and the found name refers to an instance member function, otherwise
  1742. // the function calling DiagnoseEmptyLookup will try to create an
  1743. // implicit member call and this is wrong for default argument.
  1744. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1745. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1746. return true;
  1747. }
  1748. // Tell the callee to try to recover.
  1749. return false;
  1750. }
  1751. R.clear();
  1752. }
  1753. // In Microsoft mode, if we are performing lookup from within a friend
  1754. // function definition declared at class scope then we must set
  1755. // DC to the lexical parent to be able to search into the parent
  1756. // class.
  1757. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1758. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1759. DC->getLexicalParent()->isRecord())
  1760. DC = DC->getLexicalParent();
  1761. else
  1762. DC = DC->getParent();
  1763. }
  1764. // We didn't find anything, so try to correct for a typo.
  1765. TypoCorrection Corrected;
  1766. if (S && Out) {
  1767. SourceLocation TypoLoc = R.getNameLoc();
  1768. assert(!ExplicitTemplateArgs &&
  1769. "Diagnosing an empty lookup with explicit template args!");
  1770. *Out = CorrectTypoDelayed(
  1771. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
  1772. [=](const TypoCorrection &TC) {
  1773. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1774. diagnostic, diagnostic_suggest);
  1775. },
  1776. nullptr, CTK_ErrorRecovery);
  1777. if (*Out)
  1778. return true;
  1779. } else if (S &&
  1780. (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
  1781. S, &SS, CCC, CTK_ErrorRecovery))) {
  1782. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1783. bool DroppedSpecifier =
  1784. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1785. R.setLookupName(Corrected.getCorrection());
  1786. bool AcceptableWithRecovery = false;
  1787. bool AcceptableWithoutRecovery = false;
  1788. NamedDecl *ND = Corrected.getFoundDecl();
  1789. if (ND) {
  1790. if (Corrected.isOverloaded()) {
  1791. OverloadCandidateSet OCS(R.getNameLoc(),
  1792. OverloadCandidateSet::CSK_Normal);
  1793. OverloadCandidateSet::iterator Best;
  1794. for (NamedDecl *CD : Corrected) {
  1795. if (FunctionTemplateDecl *FTD =
  1796. dyn_cast<FunctionTemplateDecl>(CD))
  1797. AddTemplateOverloadCandidate(
  1798. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1799. Args, OCS);
  1800. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1801. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1802. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1803. Args, OCS);
  1804. }
  1805. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1806. case OR_Success:
  1807. ND = Best->FoundDecl;
  1808. Corrected.setCorrectionDecl(ND);
  1809. break;
  1810. default:
  1811. // FIXME: Arbitrarily pick the first declaration for the note.
  1812. Corrected.setCorrectionDecl(ND);
  1813. break;
  1814. }
  1815. }
  1816. R.addDecl(ND);
  1817. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1818. CXXRecordDecl *Record = nullptr;
  1819. if (Corrected.getCorrectionSpecifier()) {
  1820. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1821. Record = Ty->getAsCXXRecordDecl();
  1822. }
  1823. if (!Record)
  1824. Record = cast<CXXRecordDecl>(
  1825. ND->getDeclContext()->getRedeclContext());
  1826. R.setNamingClass(Record);
  1827. }
  1828. auto *UnderlyingND = ND->getUnderlyingDecl();
  1829. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1830. isa<FunctionTemplateDecl>(UnderlyingND);
  1831. // FIXME: If we ended up with a typo for a type name or
  1832. // Objective-C class name, we're in trouble because the parser
  1833. // is in the wrong place to recover. Suggest the typo
  1834. // correction, but don't make it a fix-it since we're not going
  1835. // to recover well anyway.
  1836. AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
  1837. getAsTypeTemplateDecl(UnderlyingND) ||
  1838. isa<ObjCInterfaceDecl>(UnderlyingND);
  1839. } else {
  1840. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1841. // because we aren't able to recover.
  1842. AcceptableWithoutRecovery = true;
  1843. }
  1844. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1845. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1846. ? diag::note_implicit_param_decl
  1847. : diag::note_previous_decl;
  1848. if (SS.isEmpty())
  1849. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1850. PDiag(NoteID), AcceptableWithRecovery);
  1851. else
  1852. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1853. << Name << computeDeclContext(SS, false)
  1854. << DroppedSpecifier << SS.getRange(),
  1855. PDiag(NoteID), AcceptableWithRecovery);
  1856. // Tell the callee whether to try to recover.
  1857. return !AcceptableWithRecovery;
  1858. }
  1859. }
  1860. R.clear();
  1861. // Emit a special diagnostic for failed member lookups.
  1862. // FIXME: computing the declaration context might fail here (?)
  1863. if (!SS.isEmpty()) {
  1864. Diag(R.getNameLoc(), diag::err_no_member)
  1865. << Name << computeDeclContext(SS, false)
  1866. << SS.getRange();
  1867. return true;
  1868. }
  1869. // Give up, we can't recover.
  1870. Diag(R.getNameLoc(), diagnostic) << Name;
  1871. return true;
  1872. }
  1873. /// In Microsoft mode, if we are inside a template class whose parent class has
  1874. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1875. /// assume the identifier is a member of a dependent base class. We can only
  1876. /// recover successfully in static methods, instance methods, and other contexts
  1877. /// where 'this' is available. This doesn't precisely match MSVC's
  1878. /// instantiation model, but it's close enough.
  1879. static Expr *
  1880. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1881. DeclarationNameInfo &NameInfo,
  1882. SourceLocation TemplateKWLoc,
  1883. const TemplateArgumentListInfo *TemplateArgs) {
  1884. // Only try to recover from lookup into dependent bases in static methods or
  1885. // contexts where 'this' is available.
  1886. QualType ThisType = S.getCurrentThisType();
  1887. const CXXRecordDecl *RD = nullptr;
  1888. if (!ThisType.isNull())
  1889. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1890. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1891. RD = MD->getParent();
  1892. if (!RD || !RD->hasAnyDependentBases())
  1893. return nullptr;
  1894. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1895. // is available, suggest inserting 'this->' as a fixit.
  1896. SourceLocation Loc = NameInfo.getLoc();
  1897. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1898. DB << NameInfo.getName() << RD;
  1899. if (!ThisType.isNull()) {
  1900. DB << FixItHint::CreateInsertion(Loc, "this->");
  1901. return CXXDependentScopeMemberExpr::Create(
  1902. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1903. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1904. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
  1905. }
  1906. // Synthesize a fake NNS that points to the derived class. This will
  1907. // perform name lookup during template instantiation.
  1908. CXXScopeSpec SS;
  1909. auto *NNS =
  1910. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1911. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1912. return DependentScopeDeclRefExpr::Create(
  1913. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1914. TemplateArgs);
  1915. }
  1916. ExprResult
  1917. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1918. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1919. bool HasTrailingLParen, bool IsAddressOfOperand,
  1920. CorrectionCandidateCallback *CCC,
  1921. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1922. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1923. "cannot be direct & operand and have a trailing lparen");
  1924. if (SS.isInvalid())
  1925. return ExprError();
  1926. TemplateArgumentListInfo TemplateArgsBuffer;
  1927. // Decompose the UnqualifiedId into the following data.
  1928. DeclarationNameInfo NameInfo;
  1929. const TemplateArgumentListInfo *TemplateArgs;
  1930. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1931. DeclarationName Name = NameInfo.getName();
  1932. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1933. SourceLocation NameLoc = NameInfo.getLoc();
  1934. if (II && II->isEditorPlaceholder()) {
  1935. // FIXME: When typed placeholders are supported we can create a typed
  1936. // placeholder expression node.
  1937. return ExprError();
  1938. }
  1939. // C++ [temp.dep.expr]p3:
  1940. // An id-expression is type-dependent if it contains:
  1941. // -- an identifier that was declared with a dependent type,
  1942. // (note: handled after lookup)
  1943. // -- a template-id that is dependent,
  1944. // (note: handled in BuildTemplateIdExpr)
  1945. // -- a conversion-function-id that specifies a dependent type,
  1946. // -- a nested-name-specifier that contains a class-name that
  1947. // names a dependent type.
  1948. // Determine whether this is a member of an unknown specialization;
  1949. // we need to handle these differently.
  1950. bool DependentID = false;
  1951. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1952. Name.getCXXNameType()->isDependentType()) {
  1953. DependentID = true;
  1954. } else if (SS.isSet()) {
  1955. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1956. if (RequireCompleteDeclContext(SS, DC))
  1957. return ExprError();
  1958. } else {
  1959. DependentID = true;
  1960. }
  1961. }
  1962. if (DependentID)
  1963. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1964. IsAddressOfOperand, TemplateArgs);
  1965. // Perform the required lookup.
  1966. LookupResult R(*this, NameInfo,
  1967. (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
  1968. ? LookupObjCImplicitSelfParam
  1969. : LookupOrdinaryName);
  1970. if (TemplateKWLoc.isValid() || TemplateArgs) {
  1971. // Lookup the template name again to correctly establish the context in
  1972. // which it was found. This is really unfortunate as we already did the
  1973. // lookup to determine that it was a template name in the first place. If
  1974. // this becomes a performance hit, we can work harder to preserve those
  1975. // results until we get here but it's likely not worth it.
  1976. bool MemberOfUnknownSpecialization;
  1977. AssumedTemplateKind AssumedTemplate;
  1978. if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1979. MemberOfUnknownSpecialization, TemplateKWLoc,
  1980. &AssumedTemplate))
  1981. return ExprError();
  1982. if (MemberOfUnknownSpecialization ||
  1983. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1984. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1985. IsAddressOfOperand, TemplateArgs);
  1986. } else {
  1987. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1988. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1989. // If the result might be in a dependent base class, this is a dependent
  1990. // id-expression.
  1991. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1992. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1993. IsAddressOfOperand, TemplateArgs);
  1994. // If this reference is in an Objective-C method, then we need to do
  1995. // some special Objective-C lookup, too.
  1996. if (IvarLookupFollowUp) {
  1997. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1998. if (E.isInvalid())
  1999. return ExprError();
  2000. if (Expr *Ex = E.getAs<Expr>())
  2001. return Ex;
  2002. }
  2003. }
  2004. if (R.isAmbiguous())
  2005. return ExprError();
  2006. // This could be an implicitly declared function reference (legal in C90,
  2007. // extension in C99, forbidden in C++).
  2008. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  2009. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  2010. if (D) R.addDecl(D);
  2011. }
  2012. // Determine whether this name might be a candidate for
  2013. // argument-dependent lookup.
  2014. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  2015. if (R.empty() && !ADL) {
  2016. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  2017. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  2018. TemplateKWLoc, TemplateArgs))
  2019. return E;
  2020. }
  2021. // Don't diagnose an empty lookup for inline assembly.
  2022. if (IsInlineAsmIdentifier)
  2023. return ExprError();
  2024. // If this name wasn't predeclared and if this is not a function
  2025. // call, diagnose the problem.
  2026. TypoExpr *TE = nullptr;
  2027. DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
  2028. : nullptr);
  2029. DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
  2030. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  2031. "Typo correction callback misconfigured");
  2032. if (CCC) {
  2033. // Make sure the callback knows what the typo being diagnosed is.
  2034. CCC->setTypoName(II);
  2035. if (SS.isValid())
  2036. CCC->setTypoNNS(SS.getScopeRep());
  2037. }
  2038. // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
  2039. // a template name, but we happen to have always already looked up the name
  2040. // before we get here if it must be a template name.
  2041. if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
  2042. None, &TE)) {
  2043. if (TE && KeywordReplacement) {
  2044. auto &State = getTypoExprState(TE);
  2045. auto BestTC = State.Consumer->getNextCorrection();
  2046. if (BestTC.isKeyword()) {
  2047. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  2048. if (State.DiagHandler)
  2049. State.DiagHandler(BestTC);
  2050. KeywordReplacement->startToken();
  2051. KeywordReplacement->setKind(II->getTokenID());
  2052. KeywordReplacement->setIdentifierInfo(II);
  2053. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  2054. // Clean up the state associated with the TypoExpr, since it has
  2055. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  2056. clearDelayedTypo(TE);
  2057. // Signal that a correction to a keyword was performed by returning a
  2058. // valid-but-null ExprResult.
  2059. return (Expr*)nullptr;
  2060. }
  2061. State.Consumer->resetCorrectionStream();
  2062. }
  2063. return TE ? TE : ExprError();
  2064. }
  2065. assert(!R.empty() &&
  2066. "DiagnoseEmptyLookup returned false but added no results");
  2067. // If we found an Objective-C instance variable, let
  2068. // LookupInObjCMethod build the appropriate expression to
  2069. // reference the ivar.
  2070. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  2071. R.clear();
  2072. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  2073. // In a hopelessly buggy code, Objective-C instance variable
  2074. // lookup fails and no expression will be built to reference it.
  2075. if (!E.isInvalid() && !E.get())
  2076. return ExprError();
  2077. return E;
  2078. }
  2079. }
  2080. // This is guaranteed from this point on.
  2081. assert(!R.empty() || ADL);
  2082. // Check whether this might be a C++ implicit instance member access.
  2083. // C++ [class.mfct.non-static]p3:
  2084. // When an id-expression that is not part of a class member access
  2085. // syntax and not used to form a pointer to member is used in the
  2086. // body of a non-static member function of class X, if name lookup
  2087. // resolves the name in the id-expression to a non-static non-type
  2088. // member of some class C, the id-expression is transformed into a
  2089. // class member access expression using (*this) as the
  2090. // postfix-expression to the left of the . operator.
  2091. //
  2092. // But we don't actually need to do this for '&' operands if R
  2093. // resolved to a function or overloaded function set, because the
  2094. // expression is ill-formed if it actually works out to be a
  2095. // non-static member function:
  2096. //
  2097. // C++ [expr.ref]p4:
  2098. // Otherwise, if E1.E2 refers to a non-static member function. . .
  2099. // [t]he expression can be used only as the left-hand operand of a
  2100. // member function call.
  2101. //
  2102. // There are other safeguards against such uses, but it's important
  2103. // to get this right here so that we don't end up making a
  2104. // spuriously dependent expression if we're inside a dependent
  2105. // instance method.
  2106. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  2107. bool MightBeImplicitMember;
  2108. if (!IsAddressOfOperand)
  2109. MightBeImplicitMember = true;
  2110. else if (!SS.isEmpty())
  2111. MightBeImplicitMember = false;
  2112. else if (R.isOverloadedResult())
  2113. MightBeImplicitMember = false;
  2114. else if (R.isUnresolvableResult())
  2115. MightBeImplicitMember = true;
  2116. else
  2117. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  2118. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  2119. isa<MSPropertyDecl>(R.getFoundDecl());
  2120. if (MightBeImplicitMember)
  2121. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  2122. R, TemplateArgs, S);
  2123. }
  2124. if (TemplateArgs || TemplateKWLoc.isValid()) {
  2125. // In C++1y, if this is a variable template id, then check it
  2126. // in BuildTemplateIdExpr().
  2127. // The single lookup result must be a variable template declaration.
  2128. if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
  2129. Id.TemplateId->Kind == TNK_Var_template) {
  2130. assert(R.getAsSingle<VarTemplateDecl>() &&
  2131. "There should only be one declaration found.");
  2132. }
  2133. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  2134. }
  2135. return BuildDeclarationNameExpr(SS, R, ADL);
  2136. }
  2137. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  2138. /// declaration name, generally during template instantiation.
  2139. /// There's a large number of things which don't need to be done along
  2140. /// this path.
  2141. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  2142. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  2143. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  2144. DeclContext *DC = computeDeclContext(SS, false);
  2145. if (!DC)
  2146. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2147. NameInfo, /*TemplateArgs=*/nullptr);
  2148. if (RequireCompleteDeclContext(SS, DC))
  2149. return ExprError();
  2150. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2151. LookupQualifiedName(R, DC);
  2152. if (R.isAmbiguous())
  2153. return ExprError();
  2154. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2155. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2156. NameInfo, /*TemplateArgs=*/nullptr);
  2157. if (R.empty()) {
  2158. Diag(NameInfo.getLoc(), diag::err_no_member)
  2159. << NameInfo.getName() << DC << SS.getRange();
  2160. return ExprError();
  2161. }
  2162. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2163. // Diagnose a missing typename if this resolved unambiguously to a type in
  2164. // a dependent context. If we can recover with a type, downgrade this to
  2165. // a warning in Microsoft compatibility mode.
  2166. unsigned DiagID = diag::err_typename_missing;
  2167. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2168. DiagID = diag::ext_typename_missing;
  2169. SourceLocation Loc = SS.getBeginLoc();
  2170. auto D = Diag(Loc, DiagID);
  2171. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2172. << SourceRange(Loc, NameInfo.getEndLoc());
  2173. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2174. // context.
  2175. if (!RecoveryTSI)
  2176. return ExprError();
  2177. // Only issue the fixit if we're prepared to recover.
  2178. D << FixItHint::CreateInsertion(Loc, "typename ");
  2179. // Recover by pretending this was an elaborated type.
  2180. QualType Ty = Context.getTypeDeclType(TD);
  2181. TypeLocBuilder TLB;
  2182. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2183. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2184. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2185. QTL.setElaboratedKeywordLoc(SourceLocation());
  2186. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2187. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2188. return ExprEmpty();
  2189. }
  2190. // Defend against this resolving to an implicit member access. We usually
  2191. // won't get here if this might be a legitimate a class member (we end up in
  2192. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2193. // a pointer-to-member or in an unevaluated context in C++11.
  2194. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2195. return BuildPossibleImplicitMemberExpr(SS,
  2196. /*TemplateKWLoc=*/SourceLocation(),
  2197. R, /*TemplateArgs=*/nullptr, S);
  2198. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2199. }
  2200. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2201. /// detected that we're currently inside an ObjC method. Perform some
  2202. /// additional lookup.
  2203. ///
  2204. /// Ideally, most of this would be done by lookup, but there's
  2205. /// actually quite a lot of extra work involved.
  2206. ///
  2207. /// Returns a null sentinel to indicate trivial success.
  2208. ExprResult
  2209. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2210. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2211. SourceLocation Loc = Lookup.getNameLoc();
  2212. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2213. // Check for error condition which is already reported.
  2214. if (!CurMethod)
  2215. return ExprError();
  2216. // There are two cases to handle here. 1) scoped lookup could have failed,
  2217. // in which case we should look for an ivar. 2) scoped lookup could have
  2218. // found a decl, but that decl is outside the current instance method (i.e.
  2219. // a global variable). In these two cases, we do a lookup for an ivar with
  2220. // this name, if the lookup sucedes, we replace it our current decl.
  2221. // If we're in a class method, we don't normally want to look for
  2222. // ivars. But if we don't find anything else, and there's an
  2223. // ivar, that's an error.
  2224. bool IsClassMethod = CurMethod->isClassMethod();
  2225. bool LookForIvars;
  2226. if (Lookup.empty())
  2227. LookForIvars = true;
  2228. else if (IsClassMethod)
  2229. LookForIvars = false;
  2230. else
  2231. LookForIvars = (Lookup.isSingleResult() &&
  2232. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2233. ObjCInterfaceDecl *IFace = nullptr;
  2234. if (LookForIvars) {
  2235. IFace = CurMethod->getClassInterface();
  2236. ObjCInterfaceDecl *ClassDeclared;
  2237. ObjCIvarDecl *IV = nullptr;
  2238. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2239. // Diagnose using an ivar in a class method.
  2240. if (IsClassMethod)
  2241. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2242. << IV->getDeclName());
  2243. // If we're referencing an invalid decl, just return this as a silent
  2244. // error node. The error diagnostic was already emitted on the decl.
  2245. if (IV->isInvalidDecl())
  2246. return ExprError();
  2247. // Check if referencing a field with __attribute__((deprecated)).
  2248. if (DiagnoseUseOfDecl(IV, Loc))
  2249. return ExprError();
  2250. // Diagnose the use of an ivar outside of the declaring class.
  2251. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2252. !declaresSameEntity(ClassDeclared, IFace) &&
  2253. !getLangOpts().DebuggerSupport)
  2254. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2255. // FIXME: This should use a new expr for a direct reference, don't
  2256. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2257. IdentifierInfo &II = Context.Idents.get("self");
  2258. UnqualifiedId SelfName;
  2259. SelfName.setIdentifier(&II, SourceLocation());
  2260. SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
  2261. CXXScopeSpec SelfScopeSpec;
  2262. SourceLocation TemplateKWLoc;
  2263. ExprResult SelfExpr =
  2264. ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
  2265. /*HasTrailingLParen=*/false,
  2266. /*IsAddressOfOperand=*/false);
  2267. if (SelfExpr.isInvalid())
  2268. return ExprError();
  2269. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2270. if (SelfExpr.isInvalid())
  2271. return ExprError();
  2272. MarkAnyDeclReferenced(Loc, IV, true);
  2273. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2274. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2275. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2276. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2277. ObjCIvarRefExpr *Result = new (Context)
  2278. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2279. IV->getLocation(), SelfExpr.get(), true, true);
  2280. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2281. if (!isUnevaluatedContext() &&
  2282. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2283. getCurFunction()->recordUseOfWeak(Result);
  2284. }
  2285. if (getLangOpts().ObjCAutoRefCount)
  2286. if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
  2287. ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
  2288. return Result;
  2289. }
  2290. } else if (CurMethod->isInstanceMethod()) {
  2291. // We should warn if a local variable hides an ivar.
  2292. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2293. ObjCInterfaceDecl *ClassDeclared;
  2294. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2295. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2296. declaresSameEntity(IFace, ClassDeclared))
  2297. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2298. }
  2299. }
  2300. } else if (Lookup.isSingleResult() &&
  2301. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2302. // If accessing a stand-alone ivar in a class method, this is an error.
  2303. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2304. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2305. << IV->getDeclName());
  2306. }
  2307. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2308. // FIXME. Consolidate this with similar code in LookupName.
  2309. if (unsigned BuiltinID = II->getBuiltinID()) {
  2310. if (!(getLangOpts().CPlusPlus &&
  2311. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2312. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2313. S, Lookup.isForRedeclaration(),
  2314. Lookup.getNameLoc());
  2315. if (D) Lookup.addDecl(D);
  2316. }
  2317. }
  2318. }
  2319. // Sentinel value saying that we didn't do anything special.
  2320. return ExprResult((Expr *)nullptr);
  2321. }
  2322. /// Cast a base object to a member's actual type.
  2323. ///
  2324. /// Logically this happens in three phases:
  2325. ///
  2326. /// * First we cast from the base type to the naming class.
  2327. /// The naming class is the class into which we were looking
  2328. /// when we found the member; it's the qualifier type if a
  2329. /// qualifier was provided, and otherwise it's the base type.
  2330. ///
  2331. /// * Next we cast from the naming class to the declaring class.
  2332. /// If the member we found was brought into a class's scope by
  2333. /// a using declaration, this is that class; otherwise it's
  2334. /// the class declaring the member.
  2335. ///
  2336. /// * Finally we cast from the declaring class to the "true"
  2337. /// declaring class of the member. This conversion does not
  2338. /// obey access control.
  2339. ExprResult
  2340. Sema::PerformObjectMemberConversion(Expr *From,
  2341. NestedNameSpecifier *Qualifier,
  2342. NamedDecl *FoundDecl,
  2343. NamedDecl *Member) {
  2344. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2345. if (!RD)
  2346. return From;
  2347. QualType DestRecordType;
  2348. QualType DestType;
  2349. QualType FromRecordType;
  2350. QualType FromType = From->getType();
  2351. bool PointerConversions = false;
  2352. if (isa<FieldDecl>(Member)) {
  2353. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2354. auto FromPtrType = FromType->getAs<PointerType>();
  2355. DestRecordType = Context.getAddrSpaceQualType(
  2356. DestRecordType, FromPtrType
  2357. ? FromType->getPointeeType().getAddressSpace()
  2358. : FromType.getAddressSpace());
  2359. if (FromPtrType) {
  2360. DestType = Context.getPointerType(DestRecordType);
  2361. FromRecordType = FromPtrType->getPointeeType();
  2362. PointerConversions = true;
  2363. } else {
  2364. DestType = DestRecordType;
  2365. FromRecordType = FromType;
  2366. }
  2367. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2368. if (Method->isStatic())
  2369. return From;
  2370. DestType = Method->getThisType();
  2371. DestRecordType = DestType->getPointeeType();
  2372. if (FromType->getAs<PointerType>()) {
  2373. FromRecordType = FromType->getPointeeType();
  2374. PointerConversions = true;
  2375. } else {
  2376. FromRecordType = FromType;
  2377. DestType = DestRecordType;
  2378. }
  2379. } else {
  2380. // No conversion necessary.
  2381. return From;
  2382. }
  2383. if (DestType->isDependentType() || FromType->isDependentType())
  2384. return From;
  2385. // If the unqualified types are the same, no conversion is necessary.
  2386. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2387. return From;
  2388. SourceRange FromRange = From->getSourceRange();
  2389. SourceLocation FromLoc = FromRange.getBegin();
  2390. ExprValueKind VK = From->getValueKind();
  2391. // C++ [class.member.lookup]p8:
  2392. // [...] Ambiguities can often be resolved by qualifying a name with its
  2393. // class name.
  2394. //
  2395. // If the member was a qualified name and the qualified referred to a
  2396. // specific base subobject type, we'll cast to that intermediate type
  2397. // first and then to the object in which the member is declared. That allows
  2398. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2399. //
  2400. // class Base { public: int x; };
  2401. // class Derived1 : public Base { };
  2402. // class Derived2 : public Base { };
  2403. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2404. //
  2405. // void VeryDerived::f() {
  2406. // x = 17; // error: ambiguous base subobjects
  2407. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2408. // }
  2409. if (Qualifier && Qualifier->getAsType()) {
  2410. QualType QType = QualType(Qualifier->getAsType(), 0);
  2411. assert(QType->isRecordType() && "lookup done with non-record type");
  2412. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2413. // In C++98, the qualifier type doesn't actually have to be a base
  2414. // type of the object type, in which case we just ignore it.
  2415. // Otherwise build the appropriate casts.
  2416. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2417. CXXCastPath BasePath;
  2418. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2419. FromLoc, FromRange, &BasePath))
  2420. return ExprError();
  2421. if (PointerConversions)
  2422. QType = Context.getPointerType(QType);
  2423. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2424. VK, &BasePath).get();
  2425. FromType = QType;
  2426. FromRecordType = QRecordType;
  2427. // If the qualifier type was the same as the destination type,
  2428. // we're done.
  2429. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2430. return From;
  2431. }
  2432. }
  2433. bool IgnoreAccess = false;
  2434. // If we actually found the member through a using declaration, cast
  2435. // down to the using declaration's type.
  2436. //
  2437. // Pointer equality is fine here because only one declaration of a
  2438. // class ever has member declarations.
  2439. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2440. assert(isa<UsingShadowDecl>(FoundDecl));
  2441. QualType URecordType = Context.getTypeDeclType(
  2442. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2443. // We only need to do this if the naming-class to declaring-class
  2444. // conversion is non-trivial.
  2445. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2446. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2447. CXXCastPath BasePath;
  2448. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2449. FromLoc, FromRange, &BasePath))
  2450. return ExprError();
  2451. QualType UType = URecordType;
  2452. if (PointerConversions)
  2453. UType = Context.getPointerType(UType);
  2454. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2455. VK, &BasePath).get();
  2456. FromType = UType;
  2457. FromRecordType = URecordType;
  2458. }
  2459. // We don't do access control for the conversion from the
  2460. // declaring class to the true declaring class.
  2461. IgnoreAccess = true;
  2462. }
  2463. CXXCastPath BasePath;
  2464. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2465. FromLoc, FromRange, &BasePath,
  2466. IgnoreAccess))
  2467. return ExprError();
  2468. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2469. VK, &BasePath);
  2470. }
  2471. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2472. const LookupResult &R,
  2473. bool HasTrailingLParen) {
  2474. // Only when used directly as the postfix-expression of a call.
  2475. if (!HasTrailingLParen)
  2476. return false;
  2477. // Never if a scope specifier was provided.
  2478. if (SS.isSet())
  2479. return false;
  2480. // Only in C++ or ObjC++.
  2481. if (!getLangOpts().CPlusPlus)
  2482. return false;
  2483. // Turn off ADL when we find certain kinds of declarations during
  2484. // normal lookup:
  2485. for (NamedDecl *D : R) {
  2486. // C++0x [basic.lookup.argdep]p3:
  2487. // -- a declaration of a class member
  2488. // Since using decls preserve this property, we check this on the
  2489. // original decl.
  2490. if (D->isCXXClassMember())
  2491. return false;
  2492. // C++0x [basic.lookup.argdep]p3:
  2493. // -- a block-scope function declaration that is not a
  2494. // using-declaration
  2495. // NOTE: we also trigger this for function templates (in fact, we
  2496. // don't check the decl type at all, since all other decl types
  2497. // turn off ADL anyway).
  2498. if (isa<UsingShadowDecl>(D))
  2499. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2500. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2501. return false;
  2502. // C++0x [basic.lookup.argdep]p3:
  2503. // -- a declaration that is neither a function or a function
  2504. // template
  2505. // And also for builtin functions.
  2506. if (isa<FunctionDecl>(D)) {
  2507. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2508. // But also builtin functions.
  2509. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2510. return false;
  2511. } else if (!isa<FunctionTemplateDecl>(D))
  2512. return false;
  2513. }
  2514. return true;
  2515. }
  2516. /// Diagnoses obvious problems with the use of the given declaration
  2517. /// as an expression. This is only actually called for lookups that
  2518. /// were not overloaded, and it doesn't promise that the declaration
  2519. /// will in fact be used.
  2520. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2521. if (D->isInvalidDecl())
  2522. return true;
  2523. if (isa<TypedefNameDecl>(D)) {
  2524. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2525. return true;
  2526. }
  2527. if (isa<ObjCInterfaceDecl>(D)) {
  2528. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2529. return true;
  2530. }
  2531. if (isa<NamespaceDecl>(D)) {
  2532. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2533. return true;
  2534. }
  2535. return false;
  2536. }
  2537. // Certain multiversion types should be treated as overloaded even when there is
  2538. // only one result.
  2539. static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
  2540. assert(R.isSingleResult() && "Expected only a single result");
  2541. const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  2542. return FD &&
  2543. (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
  2544. }
  2545. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2546. LookupResult &R, bool NeedsADL,
  2547. bool AcceptInvalidDecl) {
  2548. // If this is a single, fully-resolved result and we don't need ADL,
  2549. // just build an ordinary singleton decl ref.
  2550. if (!NeedsADL && R.isSingleResult() &&
  2551. !R.getAsSingle<FunctionTemplateDecl>() &&
  2552. !ShouldLookupResultBeMultiVersionOverload(R))
  2553. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2554. R.getRepresentativeDecl(), nullptr,
  2555. AcceptInvalidDecl);
  2556. // We only need to check the declaration if there's exactly one
  2557. // result, because in the overloaded case the results can only be
  2558. // functions and function templates.
  2559. if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
  2560. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2561. return ExprError();
  2562. // Otherwise, just build an unresolved lookup expression. Suppress
  2563. // any lookup-related diagnostics; we'll hash these out later, when
  2564. // we've picked a target.
  2565. R.suppressDiagnostics();
  2566. UnresolvedLookupExpr *ULE
  2567. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2568. SS.getWithLocInContext(Context),
  2569. R.getLookupNameInfo(),
  2570. NeedsADL, R.isOverloadedResult(),
  2571. R.begin(), R.end());
  2572. return ULE;
  2573. }
  2574. static void
  2575. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2576. ValueDecl *var, DeclContext *DC);
  2577. /// Complete semantic analysis for a reference to the given declaration.
  2578. ExprResult Sema::BuildDeclarationNameExpr(
  2579. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2580. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2581. bool AcceptInvalidDecl) {
  2582. assert(D && "Cannot refer to a NULL declaration");
  2583. assert(!isa<FunctionTemplateDecl>(D) &&
  2584. "Cannot refer unambiguously to a function template");
  2585. SourceLocation Loc = NameInfo.getLoc();
  2586. if (CheckDeclInExpr(*this, Loc, D))
  2587. return ExprError();
  2588. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2589. // Specifically diagnose references to class templates that are missing
  2590. // a template argument list.
  2591. diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
  2592. return ExprError();
  2593. }
  2594. // Make sure that we're referring to a value.
  2595. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2596. if (!VD) {
  2597. Diag(Loc, diag::err_ref_non_value)
  2598. << D << SS.getRange();
  2599. Diag(D->getLocation(), diag::note_declared_at);
  2600. return ExprError();
  2601. }
  2602. // Check whether this declaration can be used. Note that we suppress
  2603. // this check when we're going to perform argument-dependent lookup
  2604. // on this function name, because this might not be the function
  2605. // that overload resolution actually selects.
  2606. if (DiagnoseUseOfDecl(VD, Loc))
  2607. return ExprError();
  2608. // Only create DeclRefExpr's for valid Decl's.
  2609. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2610. return ExprError();
  2611. // Handle members of anonymous structs and unions. If we got here,
  2612. // and the reference is to a class member indirect field, then this
  2613. // must be the subject of a pointer-to-member expression.
  2614. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2615. if (!indirectField->isCXXClassMember())
  2616. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2617. indirectField);
  2618. {
  2619. QualType type = VD->getType();
  2620. if (type.isNull())
  2621. return ExprError();
  2622. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2623. // C++ [except.spec]p17:
  2624. // An exception-specification is considered to be needed when:
  2625. // - in an expression, the function is the unique lookup result or
  2626. // the selected member of a set of overloaded functions.
  2627. ResolveExceptionSpec(Loc, FPT);
  2628. type = VD->getType();
  2629. }
  2630. ExprValueKind valueKind = VK_RValue;
  2631. switch (D->getKind()) {
  2632. // Ignore all the non-ValueDecl kinds.
  2633. #define ABSTRACT_DECL(kind)
  2634. #define VALUE(type, base)
  2635. #define DECL(type, base) \
  2636. case Decl::type:
  2637. #include "clang/AST/DeclNodes.inc"
  2638. llvm_unreachable("invalid value decl kind");
  2639. // These shouldn't make it here.
  2640. case Decl::ObjCAtDefsField:
  2641. llvm_unreachable("forming non-member reference to ivar?");
  2642. // Enum constants are always r-values and never references.
  2643. // Unresolved using declarations are dependent.
  2644. case Decl::EnumConstant:
  2645. case Decl::UnresolvedUsingValue:
  2646. case Decl::OMPDeclareReduction:
  2647. case Decl::OMPDeclareMapper:
  2648. valueKind = VK_RValue;
  2649. break;
  2650. // Fields and indirect fields that got here must be for
  2651. // pointer-to-member expressions; we just call them l-values for
  2652. // internal consistency, because this subexpression doesn't really
  2653. // exist in the high-level semantics.
  2654. case Decl::Field:
  2655. case Decl::IndirectField:
  2656. case Decl::ObjCIvar:
  2657. assert(getLangOpts().CPlusPlus &&
  2658. "building reference to field in C?");
  2659. // These can't have reference type in well-formed programs, but
  2660. // for internal consistency we do this anyway.
  2661. type = type.getNonReferenceType();
  2662. valueKind = VK_LValue;
  2663. break;
  2664. // Non-type template parameters are either l-values or r-values
  2665. // depending on the type.
  2666. case Decl::NonTypeTemplateParm: {
  2667. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2668. type = reftype->getPointeeType();
  2669. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2670. break;
  2671. }
  2672. // For non-references, we need to strip qualifiers just in case
  2673. // the template parameter was declared as 'const int' or whatever.
  2674. valueKind = VK_RValue;
  2675. type = type.getUnqualifiedType();
  2676. break;
  2677. }
  2678. case Decl::Var:
  2679. case Decl::VarTemplateSpecialization:
  2680. case Decl::VarTemplatePartialSpecialization:
  2681. case Decl::Decomposition:
  2682. case Decl::OMPCapturedExpr:
  2683. // In C, "extern void blah;" is valid and is an r-value.
  2684. if (!getLangOpts().CPlusPlus &&
  2685. !type.hasQualifiers() &&
  2686. type->isVoidType()) {
  2687. valueKind = VK_RValue;
  2688. break;
  2689. }
  2690. LLVM_FALLTHROUGH;
  2691. case Decl::ImplicitParam:
  2692. case Decl::ParmVar: {
  2693. // These are always l-values.
  2694. valueKind = VK_LValue;
  2695. type = type.getNonReferenceType();
  2696. // FIXME: Does the addition of const really only apply in
  2697. // potentially-evaluated contexts? Since the variable isn't actually
  2698. // captured in an unevaluated context, it seems that the answer is no.
  2699. if (!isUnevaluatedContext()) {
  2700. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2701. if (!CapturedType.isNull())
  2702. type = CapturedType;
  2703. }
  2704. break;
  2705. }
  2706. case Decl::Binding: {
  2707. // These are always lvalues.
  2708. valueKind = VK_LValue;
  2709. type = type.getNonReferenceType();
  2710. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2711. // decides how that's supposed to work.
  2712. auto *BD = cast<BindingDecl>(VD);
  2713. if (BD->getDeclContext() != CurContext) {
  2714. auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
  2715. if (DD && DD->hasLocalStorage())
  2716. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2717. }
  2718. break;
  2719. }
  2720. case Decl::Function: {
  2721. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2722. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2723. type = Context.BuiltinFnTy;
  2724. valueKind = VK_RValue;
  2725. break;
  2726. }
  2727. }
  2728. const FunctionType *fty = type->castAs<FunctionType>();
  2729. // If we're referring to a function with an __unknown_anytype
  2730. // result type, make the entire expression __unknown_anytype.
  2731. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2732. type = Context.UnknownAnyTy;
  2733. valueKind = VK_RValue;
  2734. break;
  2735. }
  2736. // Functions are l-values in C++.
  2737. if (getLangOpts().CPlusPlus) {
  2738. valueKind = VK_LValue;
  2739. break;
  2740. }
  2741. // C99 DR 316 says that, if a function type comes from a
  2742. // function definition (without a prototype), that type is only
  2743. // used for checking compatibility. Therefore, when referencing
  2744. // the function, we pretend that we don't have the full function
  2745. // type.
  2746. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2747. isa<FunctionProtoType>(fty))
  2748. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2749. fty->getExtInfo());
  2750. // Functions are r-values in C.
  2751. valueKind = VK_RValue;
  2752. break;
  2753. }
  2754. case Decl::CXXDeductionGuide:
  2755. llvm_unreachable("building reference to deduction guide");
  2756. case Decl::MSProperty:
  2757. valueKind = VK_LValue;
  2758. break;
  2759. case Decl::CXXMethod:
  2760. // If we're referring to a method with an __unknown_anytype
  2761. // result type, make the entire expression __unknown_anytype.
  2762. // This should only be possible with a type written directly.
  2763. if (const FunctionProtoType *proto
  2764. = dyn_cast<FunctionProtoType>(VD->getType()))
  2765. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2766. type = Context.UnknownAnyTy;
  2767. valueKind = VK_RValue;
  2768. break;
  2769. }
  2770. // C++ methods are l-values if static, r-values if non-static.
  2771. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2772. valueKind = VK_LValue;
  2773. break;
  2774. }
  2775. LLVM_FALLTHROUGH;
  2776. case Decl::CXXConversion:
  2777. case Decl::CXXDestructor:
  2778. case Decl::CXXConstructor:
  2779. valueKind = VK_RValue;
  2780. break;
  2781. }
  2782. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2783. /*FIXME: TemplateKWLoc*/ SourceLocation(),
  2784. TemplateArgs);
  2785. }
  2786. }
  2787. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2788. SmallString<32> &Target) {
  2789. Target.resize(CharByteWidth * (Source.size() + 1));
  2790. char *ResultPtr = &Target[0];
  2791. const llvm::UTF8 *ErrorPtr;
  2792. bool success =
  2793. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2794. (void)success;
  2795. assert(success);
  2796. Target.resize(ResultPtr - &Target[0]);
  2797. }
  2798. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2799. PredefinedExpr::IdentKind IK) {
  2800. // Pick the current block, lambda, captured statement or function.
  2801. Decl *currentDecl = nullptr;
  2802. if (const BlockScopeInfo *BSI = getCurBlock())
  2803. currentDecl = BSI->TheDecl;
  2804. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2805. currentDecl = LSI->CallOperator;
  2806. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2807. currentDecl = CSI->TheCapturedDecl;
  2808. else
  2809. currentDecl = getCurFunctionOrMethodDecl();
  2810. if (!currentDecl) {
  2811. Diag(Loc, diag::ext_predef_outside_function);
  2812. currentDecl = Context.getTranslationUnitDecl();
  2813. }
  2814. QualType ResTy;
  2815. StringLiteral *SL = nullptr;
  2816. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2817. ResTy = Context.DependentTy;
  2818. else {
  2819. // Pre-defined identifiers are of type char[x], where x is the length of
  2820. // the string.
  2821. auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
  2822. unsigned Length = Str.length();
  2823. llvm::APInt LengthI(32, Length + 1);
  2824. if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
  2825. ResTy =
  2826. Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
  2827. SmallString<32> RawChars;
  2828. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2829. Str, RawChars);
  2830. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2831. /*IndexTypeQuals*/ 0);
  2832. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2833. /*Pascal*/ false, ResTy, Loc);
  2834. } else {
  2835. ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
  2836. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2837. /*IndexTypeQuals*/ 0);
  2838. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2839. /*Pascal*/ false, ResTy, Loc);
  2840. }
  2841. }
  2842. return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
  2843. }
  2844. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2845. PredefinedExpr::IdentKind IK;
  2846. switch (Kind) {
  2847. default: llvm_unreachable("Unknown simple primary expr!");
  2848. case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2849. case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
  2850. case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
  2851. case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
  2852. case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
  2853. case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
  2854. case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
  2855. }
  2856. return BuildPredefinedExpr(Loc, IK);
  2857. }
  2858. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2859. SmallString<16> CharBuffer;
  2860. bool Invalid = false;
  2861. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2862. if (Invalid)
  2863. return ExprError();
  2864. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2865. PP, Tok.getKind());
  2866. if (Literal.hadError())
  2867. return ExprError();
  2868. QualType Ty;
  2869. if (Literal.isWide())
  2870. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2871. else if (Literal.isUTF8() && getLangOpts().Char8)
  2872. Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
  2873. else if (Literal.isUTF16())
  2874. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2875. else if (Literal.isUTF32())
  2876. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2877. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2878. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2879. else
  2880. Ty = Context.CharTy; // 'x' -> char in C++
  2881. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2882. if (Literal.isWide())
  2883. Kind = CharacterLiteral::Wide;
  2884. else if (Literal.isUTF16())
  2885. Kind = CharacterLiteral::UTF16;
  2886. else if (Literal.isUTF32())
  2887. Kind = CharacterLiteral::UTF32;
  2888. else if (Literal.isUTF8())
  2889. Kind = CharacterLiteral::UTF8;
  2890. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2891. Tok.getLocation());
  2892. if (Literal.getUDSuffix().empty())
  2893. return Lit;
  2894. // We're building a user-defined literal.
  2895. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2896. SourceLocation UDSuffixLoc =
  2897. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2898. // Make sure we're allowed user-defined literals here.
  2899. if (!UDLScope)
  2900. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2901. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2902. // operator "" X (ch)
  2903. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2904. Lit, Tok.getLocation());
  2905. }
  2906. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2907. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2908. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2909. Context.IntTy, Loc);
  2910. }
  2911. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2912. QualType Ty, SourceLocation Loc) {
  2913. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2914. using llvm::APFloat;
  2915. APFloat Val(Format);
  2916. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2917. // Overflow is always an error, but underflow is only an error if
  2918. // we underflowed to zero (APFloat reports denormals as underflow).
  2919. if ((result & APFloat::opOverflow) ||
  2920. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2921. unsigned diagnostic;
  2922. SmallString<20> buffer;
  2923. if (result & APFloat::opOverflow) {
  2924. diagnostic = diag::warn_float_overflow;
  2925. APFloat::getLargest(Format).toString(buffer);
  2926. } else {
  2927. diagnostic = diag::warn_float_underflow;
  2928. APFloat::getSmallest(Format).toString(buffer);
  2929. }
  2930. S.Diag(Loc, diagnostic)
  2931. << Ty
  2932. << StringRef(buffer.data(), buffer.size());
  2933. }
  2934. bool isExact = (result == APFloat::opOK);
  2935. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2936. }
  2937. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2938. assert(E && "Invalid expression");
  2939. if (E->isValueDependent())
  2940. return false;
  2941. QualType QT = E->getType();
  2942. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2943. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2944. return true;
  2945. }
  2946. llvm::APSInt ValueAPS;
  2947. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2948. if (R.isInvalid())
  2949. return true;
  2950. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2951. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2952. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2953. << ValueAPS.toString(10) << ValueIsPositive;
  2954. return true;
  2955. }
  2956. return false;
  2957. }
  2958. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2959. // Fast path for a single digit (which is quite common). A single digit
  2960. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2961. if (Tok.getLength() == 1) {
  2962. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2963. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2964. }
  2965. SmallString<128> SpellingBuffer;
  2966. // NumericLiteralParser wants to overread by one character. Add padding to
  2967. // the buffer in case the token is copied to the buffer. If getSpelling()
  2968. // returns a StringRef to the memory buffer, it should have a null char at
  2969. // the EOF, so it is also safe.
  2970. SpellingBuffer.resize(Tok.getLength() + 1);
  2971. // Get the spelling of the token, which eliminates trigraphs, etc.
  2972. bool Invalid = false;
  2973. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2974. if (Invalid)
  2975. return ExprError();
  2976. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2977. if (Literal.hadError)
  2978. return ExprError();
  2979. if (Literal.hasUDSuffix()) {
  2980. // We're building a user-defined literal.
  2981. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2982. SourceLocation UDSuffixLoc =
  2983. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2984. // Make sure we're allowed user-defined literals here.
  2985. if (!UDLScope)
  2986. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2987. QualType CookedTy;
  2988. if (Literal.isFloatingLiteral()) {
  2989. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2990. // long double, the literal is treated as a call of the form
  2991. // operator "" X (f L)
  2992. CookedTy = Context.LongDoubleTy;
  2993. } else {
  2994. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2995. // unsigned long long, the literal is treated as a call of the form
  2996. // operator "" X (n ULL)
  2997. CookedTy = Context.UnsignedLongLongTy;
  2998. }
  2999. DeclarationName OpName =
  3000. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  3001. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  3002. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  3003. SourceLocation TokLoc = Tok.getLocation();
  3004. // Perform literal operator lookup to determine if we're building a raw
  3005. // literal or a cooked one.
  3006. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  3007. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  3008. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  3009. /*AllowStringTemplate*/ false,
  3010. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  3011. case LOLR_ErrorNoDiagnostic:
  3012. // Lookup failure for imaginary constants isn't fatal, there's still the
  3013. // GNU extension producing _Complex types.
  3014. break;
  3015. case LOLR_Error:
  3016. return ExprError();
  3017. case LOLR_Cooked: {
  3018. Expr *Lit;
  3019. if (Literal.isFloatingLiteral()) {
  3020. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  3021. } else {
  3022. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  3023. if (Literal.GetIntegerValue(ResultVal))
  3024. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3025. << /* Unsigned */ 1;
  3026. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  3027. Tok.getLocation());
  3028. }
  3029. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3030. }
  3031. case LOLR_Raw: {
  3032. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  3033. // literal is treated as a call of the form
  3034. // operator "" X ("n")
  3035. unsigned Length = Literal.getUDSuffixOffset();
  3036. QualType StrTy = Context.getConstantArrayType(
  3037. Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
  3038. llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
  3039. Expr *Lit = StringLiteral::Create(
  3040. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  3041. /*Pascal*/false, StrTy, &TokLoc, 1);
  3042. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  3043. }
  3044. case LOLR_Template: {
  3045. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  3046. // template), L is treated as a call fo the form
  3047. // operator "" X <'c1', 'c2', ... 'ck'>()
  3048. // where n is the source character sequence c1 c2 ... ck.
  3049. TemplateArgumentListInfo ExplicitArgs;
  3050. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  3051. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  3052. llvm::APSInt Value(CharBits, CharIsUnsigned);
  3053. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  3054. Value = TokSpelling[I];
  3055. TemplateArgument Arg(Context, Value, Context.CharTy);
  3056. TemplateArgumentLocInfo ArgInfo;
  3057. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  3058. }
  3059. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  3060. &ExplicitArgs);
  3061. }
  3062. case LOLR_StringTemplate:
  3063. llvm_unreachable("unexpected literal operator lookup result");
  3064. }
  3065. }
  3066. Expr *Res;
  3067. if (Literal.isFixedPointLiteral()) {
  3068. QualType Ty;
  3069. if (Literal.isAccum) {
  3070. if (Literal.isHalf) {
  3071. Ty = Context.ShortAccumTy;
  3072. } else if (Literal.isLong) {
  3073. Ty = Context.LongAccumTy;
  3074. } else {
  3075. Ty = Context.AccumTy;
  3076. }
  3077. } else if (Literal.isFract) {
  3078. if (Literal.isHalf) {
  3079. Ty = Context.ShortFractTy;
  3080. } else if (Literal.isLong) {
  3081. Ty = Context.LongFractTy;
  3082. } else {
  3083. Ty = Context.FractTy;
  3084. }
  3085. }
  3086. if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
  3087. bool isSigned = !Literal.isUnsigned;
  3088. unsigned scale = Context.getFixedPointScale(Ty);
  3089. unsigned bit_width = Context.getTypeInfo(Ty).Width;
  3090. llvm::APInt Val(bit_width, 0, isSigned);
  3091. bool Overflowed = Literal.GetFixedPointValue(Val, scale);
  3092. bool ValIsZero = Val.isNullValue() && !Overflowed;
  3093. auto MaxVal = Context.getFixedPointMax(Ty).getValue();
  3094. if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
  3095. // Clause 6.4.4 - The value of a constant shall be in the range of
  3096. // representable values for its type, with exception for constants of a
  3097. // fract type with a value of exactly 1; such a constant shall denote
  3098. // the maximal value for the type.
  3099. --Val;
  3100. else if (Val.ugt(MaxVal) || Overflowed)
  3101. Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
  3102. Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
  3103. Tok.getLocation(), scale);
  3104. } else if (Literal.isFloatingLiteral()) {
  3105. QualType Ty;
  3106. if (Literal.isHalf){
  3107. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  3108. Ty = Context.HalfTy;
  3109. else {
  3110. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  3111. return ExprError();
  3112. }
  3113. } else if (Literal.isFloat)
  3114. Ty = Context.FloatTy;
  3115. else if (Literal.isLong)
  3116. Ty = Context.LongDoubleTy;
  3117. else if (Literal.isFloat16)
  3118. Ty = Context.Float16Ty;
  3119. else if (Literal.isFloat128)
  3120. Ty = Context.Float128Ty;
  3121. else
  3122. Ty = Context.DoubleTy;
  3123. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  3124. if (Ty == Context.DoubleTy) {
  3125. if (getLangOpts().SinglePrecisionConstants) {
  3126. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  3127. if (BTy->getKind() != BuiltinType::Float) {
  3128. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3129. }
  3130. } else if (getLangOpts().OpenCL &&
  3131. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  3132. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  3133. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  3134. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  3135. }
  3136. }
  3137. } else if (!Literal.isIntegerLiteral()) {
  3138. return ExprError();
  3139. } else {
  3140. QualType Ty;
  3141. // 'long long' is a C99 or C++11 feature.
  3142. if (!getLangOpts().C99 && Literal.isLongLong) {
  3143. if (getLangOpts().CPlusPlus)
  3144. Diag(Tok.getLocation(),
  3145. getLangOpts().CPlusPlus11 ?
  3146. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  3147. else
  3148. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  3149. }
  3150. // Get the value in the widest-possible width.
  3151. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  3152. llvm::APInt ResultVal(MaxWidth, 0);
  3153. if (Literal.GetIntegerValue(ResultVal)) {
  3154. // If this value didn't fit into uintmax_t, error and force to ull.
  3155. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  3156. << /* Unsigned */ 1;
  3157. Ty = Context.UnsignedLongLongTy;
  3158. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  3159. "long long is not intmax_t?");
  3160. } else {
  3161. // If this value fits into a ULL, try to figure out what else it fits into
  3162. // according to the rules of C99 6.4.4.1p5.
  3163. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  3164. // be an unsigned int.
  3165. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  3166. // Check from smallest to largest, picking the smallest type we can.
  3167. unsigned Width = 0;
  3168. // Microsoft specific integer suffixes are explicitly sized.
  3169. if (Literal.MicrosoftInteger) {
  3170. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  3171. Width = 8;
  3172. Ty = Context.CharTy;
  3173. } else {
  3174. Width = Literal.MicrosoftInteger;
  3175. Ty = Context.getIntTypeForBitwidth(Width,
  3176. /*Signed=*/!Literal.isUnsigned);
  3177. }
  3178. }
  3179. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  3180. // Are int/unsigned possibilities?
  3181. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  3182. // Does it fit in a unsigned int?
  3183. if (ResultVal.isIntN(IntSize)) {
  3184. // Does it fit in a signed int?
  3185. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  3186. Ty = Context.IntTy;
  3187. else if (AllowUnsigned)
  3188. Ty = Context.UnsignedIntTy;
  3189. Width = IntSize;
  3190. }
  3191. }
  3192. // Are long/unsigned long possibilities?
  3193. if (Ty.isNull() && !Literal.isLongLong) {
  3194. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  3195. // Does it fit in a unsigned long?
  3196. if (ResultVal.isIntN(LongSize)) {
  3197. // Does it fit in a signed long?
  3198. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  3199. Ty = Context.LongTy;
  3200. else if (AllowUnsigned)
  3201. Ty = Context.UnsignedLongTy;
  3202. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  3203. // is compatible.
  3204. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3205. const unsigned LongLongSize =
  3206. Context.getTargetInfo().getLongLongWidth();
  3207. Diag(Tok.getLocation(),
  3208. getLangOpts().CPlusPlus
  3209. ? Literal.isLong
  3210. ? diag::warn_old_implicitly_unsigned_long_cxx
  3211. : /*C++98 UB*/ diag::
  3212. ext_old_implicitly_unsigned_long_cxx
  3213. : diag::warn_old_implicitly_unsigned_long)
  3214. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3215. : /*will be ill-formed*/ 1);
  3216. Ty = Context.UnsignedLongTy;
  3217. }
  3218. Width = LongSize;
  3219. }
  3220. }
  3221. // Check long long if needed.
  3222. if (Ty.isNull()) {
  3223. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3224. // Does it fit in a unsigned long long?
  3225. if (ResultVal.isIntN(LongLongSize)) {
  3226. // Does it fit in a signed long long?
  3227. // To be compatible with MSVC, hex integer literals ending with the
  3228. // LL or i64 suffix are always signed in Microsoft mode.
  3229. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3230. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3231. Ty = Context.LongLongTy;
  3232. else if (AllowUnsigned)
  3233. Ty = Context.UnsignedLongLongTy;
  3234. Width = LongLongSize;
  3235. }
  3236. }
  3237. // If we still couldn't decide a type, we probably have something that
  3238. // does not fit in a signed long long, but has no U suffix.
  3239. if (Ty.isNull()) {
  3240. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3241. Ty = Context.UnsignedLongLongTy;
  3242. Width = Context.getTargetInfo().getLongLongWidth();
  3243. }
  3244. if (ResultVal.getBitWidth() != Width)
  3245. ResultVal = ResultVal.trunc(Width);
  3246. }
  3247. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3248. }
  3249. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3250. if (Literal.isImaginary) {
  3251. Res = new (Context) ImaginaryLiteral(Res,
  3252. Context.getComplexType(Res->getType()));
  3253. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3254. }
  3255. return Res;
  3256. }
  3257. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3258. assert(E && "ActOnParenExpr() missing expr");
  3259. return new (Context) ParenExpr(L, R, E);
  3260. }
  3261. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3262. SourceLocation Loc,
  3263. SourceRange ArgRange) {
  3264. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3265. // scalar or vector data type argument..."
  3266. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3267. // type (C99 6.2.5p18) or void.
  3268. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3269. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3270. << T << ArgRange;
  3271. return true;
  3272. }
  3273. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3274. "Scalar types should always be complete");
  3275. return false;
  3276. }
  3277. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3278. SourceLocation Loc,
  3279. SourceRange ArgRange,
  3280. UnaryExprOrTypeTrait TraitKind) {
  3281. // Invalid types must be hard errors for SFINAE in C++.
  3282. if (S.LangOpts.CPlusPlus)
  3283. return true;
  3284. // C99 6.5.3.4p1:
  3285. if (T->isFunctionType() &&
  3286. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
  3287. TraitKind == UETT_PreferredAlignOf)) {
  3288. // sizeof(function)/alignof(function) is allowed as an extension.
  3289. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3290. << TraitKind << ArgRange;
  3291. return false;
  3292. }
  3293. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3294. // this is an error (OpenCL v1.1 s6.3.k)
  3295. if (T->isVoidType()) {
  3296. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3297. : diag::ext_sizeof_alignof_void_type;
  3298. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3299. return false;
  3300. }
  3301. return true;
  3302. }
  3303. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3304. SourceLocation Loc,
  3305. SourceRange ArgRange,
  3306. UnaryExprOrTypeTrait TraitKind) {
  3307. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3308. // runtime doesn't allow it.
  3309. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3310. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3311. << T << (TraitKind == UETT_SizeOf)
  3312. << ArgRange;
  3313. return true;
  3314. }
  3315. return false;
  3316. }
  3317. /// Check whether E is a pointer from a decayed array type (the decayed
  3318. /// pointer type is equal to T) and emit a warning if it is.
  3319. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3320. Expr *E) {
  3321. // Don't warn if the operation changed the type.
  3322. if (T != E->getType())
  3323. return;
  3324. // Now look for array decays.
  3325. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3326. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3327. return;
  3328. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3329. << ICE->getType()
  3330. << ICE->getSubExpr()->getType();
  3331. }
  3332. /// Check the constraints on expression operands to unary type expression
  3333. /// and type traits.
  3334. ///
  3335. /// Completes any types necessary and validates the constraints on the operand
  3336. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3337. /// the expression as it completes the type for that expression through template
  3338. /// instantiation, etc.
  3339. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3340. UnaryExprOrTypeTrait ExprKind) {
  3341. QualType ExprTy = E->getType();
  3342. assert(!ExprTy->isReferenceType());
  3343. if (ExprKind == UETT_VecStep)
  3344. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3345. E->getSourceRange());
  3346. // Whitelist some types as extensions
  3347. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3348. E->getSourceRange(), ExprKind))
  3349. return false;
  3350. // 'alignof' applied to an expression only requires the base element type of
  3351. // the expression to be complete. 'sizeof' requires the expression's type to
  3352. // be complete (and will attempt to complete it if it's an array of unknown
  3353. // bound).
  3354. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3355. if (RequireCompleteType(E->getExprLoc(),
  3356. Context.getBaseElementType(E->getType()),
  3357. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3358. E->getSourceRange()))
  3359. return true;
  3360. } else {
  3361. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3362. ExprKind, E->getSourceRange()))
  3363. return true;
  3364. }
  3365. // Completing the expression's type may have changed it.
  3366. ExprTy = E->getType();
  3367. assert(!ExprTy->isReferenceType());
  3368. if (ExprTy->isFunctionType()) {
  3369. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3370. << ExprKind << E->getSourceRange();
  3371. return true;
  3372. }
  3373. // The operand for sizeof and alignof is in an unevaluated expression context,
  3374. // so side effects could result in unintended consequences.
  3375. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
  3376. ExprKind == UETT_PreferredAlignOf) &&
  3377. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3378. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3379. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3380. E->getSourceRange(), ExprKind))
  3381. return true;
  3382. if (ExprKind == UETT_SizeOf) {
  3383. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3384. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3385. QualType OType = PVD->getOriginalType();
  3386. QualType Type = PVD->getType();
  3387. if (Type->isPointerType() && OType->isArrayType()) {
  3388. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3389. << Type << OType;
  3390. Diag(PVD->getLocation(), diag::note_declared_at);
  3391. }
  3392. }
  3393. }
  3394. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3395. // decays into a pointer and returns an unintended result. This is most
  3396. // likely a typo for "sizeof(array) op x".
  3397. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3398. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3399. BO->getLHS());
  3400. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3401. BO->getRHS());
  3402. }
  3403. }
  3404. return false;
  3405. }
  3406. /// Check the constraints on operands to unary expression and type
  3407. /// traits.
  3408. ///
  3409. /// This will complete any types necessary, and validate the various constraints
  3410. /// on those operands.
  3411. ///
  3412. /// The UsualUnaryConversions() function is *not* called by this routine.
  3413. /// C99 6.3.2.1p[2-4] all state:
  3414. /// Except when it is the operand of the sizeof operator ...
  3415. ///
  3416. /// C++ [expr.sizeof]p4
  3417. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3418. /// standard conversions are not applied to the operand of sizeof.
  3419. ///
  3420. /// This policy is followed for all of the unary trait expressions.
  3421. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3422. SourceLocation OpLoc,
  3423. SourceRange ExprRange,
  3424. UnaryExprOrTypeTrait ExprKind) {
  3425. if (ExprType->isDependentType())
  3426. return false;
  3427. // C++ [expr.sizeof]p2:
  3428. // When applied to a reference or a reference type, the result
  3429. // is the size of the referenced type.
  3430. // C++11 [expr.alignof]p3:
  3431. // When alignof is applied to a reference type, the result
  3432. // shall be the alignment of the referenced type.
  3433. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3434. ExprType = Ref->getPointeeType();
  3435. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3436. // When alignof or _Alignof is applied to an array type, the result
  3437. // is the alignment of the element type.
  3438. if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
  3439. ExprKind == UETT_OpenMPRequiredSimdAlign)
  3440. ExprType = Context.getBaseElementType(ExprType);
  3441. if (ExprKind == UETT_VecStep)
  3442. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3443. // Whitelist some types as extensions
  3444. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3445. ExprKind))
  3446. return false;
  3447. if (RequireCompleteType(OpLoc, ExprType,
  3448. diag::err_sizeof_alignof_incomplete_type,
  3449. ExprKind, ExprRange))
  3450. return true;
  3451. if (ExprType->isFunctionType()) {
  3452. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3453. << ExprKind << ExprRange;
  3454. return true;
  3455. }
  3456. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3457. ExprKind))
  3458. return true;
  3459. return false;
  3460. }
  3461. static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
  3462. E = E->IgnoreParens();
  3463. // Cannot know anything else if the expression is dependent.
  3464. if (E->isTypeDependent())
  3465. return false;
  3466. if (E->getObjectKind() == OK_BitField) {
  3467. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3468. << 1 << E->getSourceRange();
  3469. return true;
  3470. }
  3471. ValueDecl *D = nullptr;
  3472. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3473. D = DRE->getDecl();
  3474. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3475. D = ME->getMemberDecl();
  3476. }
  3477. // If it's a field, require the containing struct to have a
  3478. // complete definition so that we can compute the layout.
  3479. //
  3480. // This can happen in C++11 onwards, either by naming the member
  3481. // in a way that is not transformed into a member access expression
  3482. // (in an unevaluated operand, for instance), or by naming the member
  3483. // in a trailing-return-type.
  3484. //
  3485. // For the record, since __alignof__ on expressions is a GCC
  3486. // extension, GCC seems to permit this but always gives the
  3487. // nonsensical answer 0.
  3488. //
  3489. // We don't really need the layout here --- we could instead just
  3490. // directly check for all the appropriate alignment-lowing
  3491. // attributes --- but that would require duplicating a lot of
  3492. // logic that just isn't worth duplicating for such a marginal
  3493. // use-case.
  3494. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3495. // Fast path this check, since we at least know the record has a
  3496. // definition if we can find a member of it.
  3497. if (!FD->getParent()->isCompleteDefinition()) {
  3498. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3499. << E->getSourceRange();
  3500. return true;
  3501. }
  3502. // Otherwise, if it's a field, and the field doesn't have
  3503. // reference type, then it must have a complete type (or be a
  3504. // flexible array member, which we explicitly want to
  3505. // white-list anyway), which makes the following checks trivial.
  3506. if (!FD->getType()->isReferenceType())
  3507. return false;
  3508. }
  3509. return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
  3510. }
  3511. bool Sema::CheckVecStepExpr(Expr *E) {
  3512. E = E->IgnoreParens();
  3513. // Cannot know anything else if the expression is dependent.
  3514. if (E->isTypeDependent())
  3515. return false;
  3516. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3517. }
  3518. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3519. CapturingScopeInfo *CSI) {
  3520. assert(T->isVariablyModifiedType());
  3521. assert(CSI != nullptr);
  3522. // We're going to walk down into the type and look for VLA expressions.
  3523. do {
  3524. const Type *Ty = T.getTypePtr();
  3525. switch (Ty->getTypeClass()) {
  3526. #define TYPE(Class, Base)
  3527. #define ABSTRACT_TYPE(Class, Base)
  3528. #define NON_CANONICAL_TYPE(Class, Base)
  3529. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3530. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3531. #include "clang/AST/TypeNodes.def"
  3532. T = QualType();
  3533. break;
  3534. // These types are never variably-modified.
  3535. case Type::Builtin:
  3536. case Type::Complex:
  3537. case Type::Vector:
  3538. case Type::ExtVector:
  3539. case Type::Record:
  3540. case Type::Enum:
  3541. case Type::Elaborated:
  3542. case Type::TemplateSpecialization:
  3543. case Type::ObjCObject:
  3544. case Type::ObjCInterface:
  3545. case Type::ObjCObjectPointer:
  3546. case Type::ObjCTypeParam:
  3547. case Type::Pipe:
  3548. llvm_unreachable("type class is never variably-modified!");
  3549. case Type::Adjusted:
  3550. T = cast<AdjustedType>(Ty)->getOriginalType();
  3551. break;
  3552. case Type::Decayed:
  3553. T = cast<DecayedType>(Ty)->getPointeeType();
  3554. break;
  3555. case Type::Pointer:
  3556. T = cast<PointerType>(Ty)->getPointeeType();
  3557. break;
  3558. case Type::BlockPointer:
  3559. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3560. break;
  3561. case Type::LValueReference:
  3562. case Type::RValueReference:
  3563. T = cast<ReferenceType>(Ty)->getPointeeType();
  3564. break;
  3565. case Type::MemberPointer:
  3566. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3567. break;
  3568. case Type::ConstantArray:
  3569. case Type::IncompleteArray:
  3570. // Losing element qualification here is fine.
  3571. T = cast<ArrayType>(Ty)->getElementType();
  3572. break;
  3573. case Type::VariableArray: {
  3574. // Losing element qualification here is fine.
  3575. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3576. // Unknown size indication requires no size computation.
  3577. // Otherwise, evaluate and record it.
  3578. auto Size = VAT->getSizeExpr();
  3579. if (Size && !CSI->isVLATypeCaptured(VAT) &&
  3580. (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
  3581. CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
  3582. T = VAT->getElementType();
  3583. break;
  3584. }
  3585. case Type::FunctionProto:
  3586. case Type::FunctionNoProto:
  3587. T = cast<FunctionType>(Ty)->getReturnType();
  3588. break;
  3589. case Type::Paren:
  3590. case Type::TypeOf:
  3591. case Type::UnaryTransform:
  3592. case Type::Attributed:
  3593. case Type::SubstTemplateTypeParm:
  3594. case Type::PackExpansion:
  3595. case Type::MacroQualified:
  3596. // Keep walking after single level desugaring.
  3597. T = T.getSingleStepDesugaredType(Context);
  3598. break;
  3599. case Type::Typedef:
  3600. T = cast<TypedefType>(Ty)->desugar();
  3601. break;
  3602. case Type::Decltype:
  3603. T = cast<DecltypeType>(Ty)->desugar();
  3604. break;
  3605. case Type::Auto:
  3606. case Type::DeducedTemplateSpecialization:
  3607. T = cast<DeducedType>(Ty)->getDeducedType();
  3608. break;
  3609. case Type::TypeOfExpr:
  3610. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3611. break;
  3612. case Type::Atomic:
  3613. T = cast<AtomicType>(Ty)->getValueType();
  3614. break;
  3615. }
  3616. } while (!T.isNull() && T->isVariablyModifiedType());
  3617. }
  3618. /// Build a sizeof or alignof expression given a type operand.
  3619. ExprResult
  3620. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3621. SourceLocation OpLoc,
  3622. UnaryExprOrTypeTrait ExprKind,
  3623. SourceRange R) {
  3624. if (!TInfo)
  3625. return ExprError();
  3626. QualType T = TInfo->getType();
  3627. if (!T->isDependentType() &&
  3628. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3629. return ExprError();
  3630. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3631. if (auto *TT = T->getAs<TypedefType>()) {
  3632. for (auto I = FunctionScopes.rbegin(),
  3633. E = std::prev(FunctionScopes.rend());
  3634. I != E; ++I) {
  3635. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3636. if (CSI == nullptr)
  3637. break;
  3638. DeclContext *DC = nullptr;
  3639. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3640. DC = LSI->CallOperator;
  3641. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3642. DC = CRSI->TheCapturedDecl;
  3643. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3644. DC = BSI->TheDecl;
  3645. if (DC) {
  3646. if (DC->containsDecl(TT->getDecl()))
  3647. break;
  3648. captureVariablyModifiedType(Context, T, CSI);
  3649. }
  3650. }
  3651. }
  3652. }
  3653. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3654. return new (Context) UnaryExprOrTypeTraitExpr(
  3655. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3656. }
  3657. /// Build a sizeof or alignof expression given an expression
  3658. /// operand.
  3659. ExprResult
  3660. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3661. UnaryExprOrTypeTrait ExprKind) {
  3662. ExprResult PE = CheckPlaceholderExpr(E);
  3663. if (PE.isInvalid())
  3664. return ExprError();
  3665. E = PE.get();
  3666. // Verify that the operand is valid.
  3667. bool isInvalid = false;
  3668. if (E->isTypeDependent()) {
  3669. // Delay type-checking for type-dependent expressions.
  3670. } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
  3671. isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
  3672. } else if (ExprKind == UETT_VecStep) {
  3673. isInvalid = CheckVecStepExpr(E);
  3674. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3675. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3676. isInvalid = true;
  3677. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3678. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3679. isInvalid = true;
  3680. } else {
  3681. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3682. }
  3683. if (isInvalid)
  3684. return ExprError();
  3685. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3686. PE = TransformToPotentiallyEvaluated(E);
  3687. if (PE.isInvalid()) return ExprError();
  3688. E = PE.get();
  3689. }
  3690. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3691. return new (Context) UnaryExprOrTypeTraitExpr(
  3692. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3693. }
  3694. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3695. /// expr and the same for @c alignof and @c __alignof
  3696. /// Note that the ArgRange is invalid if isType is false.
  3697. ExprResult
  3698. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3699. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3700. void *TyOrEx, SourceRange ArgRange) {
  3701. // If error parsing type, ignore.
  3702. if (!TyOrEx) return ExprError();
  3703. if (IsType) {
  3704. TypeSourceInfo *TInfo;
  3705. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3706. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3707. }
  3708. Expr *ArgEx = (Expr *)TyOrEx;
  3709. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3710. return Result;
  3711. }
  3712. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3713. bool IsReal) {
  3714. if (V.get()->isTypeDependent())
  3715. return S.Context.DependentTy;
  3716. // _Real and _Imag are only l-values for normal l-values.
  3717. if (V.get()->getObjectKind() != OK_Ordinary) {
  3718. V = S.DefaultLvalueConversion(V.get());
  3719. if (V.isInvalid())
  3720. return QualType();
  3721. }
  3722. // These operators return the element type of a complex type.
  3723. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3724. return CT->getElementType();
  3725. // Otherwise they pass through real integer and floating point types here.
  3726. if (V.get()->getType()->isArithmeticType())
  3727. return V.get()->getType();
  3728. // Test for placeholders.
  3729. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3730. if (PR.isInvalid()) return QualType();
  3731. if (PR.get() != V.get()) {
  3732. V = PR;
  3733. return CheckRealImagOperand(S, V, Loc, IsReal);
  3734. }
  3735. // Reject anything else.
  3736. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3737. << (IsReal ? "__real" : "__imag");
  3738. return QualType();
  3739. }
  3740. ExprResult
  3741. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3742. tok::TokenKind Kind, Expr *Input) {
  3743. UnaryOperatorKind Opc;
  3744. switch (Kind) {
  3745. default: llvm_unreachable("Unknown unary op!");
  3746. case tok::plusplus: Opc = UO_PostInc; break;
  3747. case tok::minusminus: Opc = UO_PostDec; break;
  3748. }
  3749. // Since this might is a postfix expression, get rid of ParenListExprs.
  3750. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3751. if (Result.isInvalid()) return ExprError();
  3752. Input = Result.get();
  3753. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3754. }
  3755. /// Diagnose if arithmetic on the given ObjC pointer is illegal.
  3756. ///
  3757. /// \return true on error
  3758. static bool checkArithmeticOnObjCPointer(Sema &S,
  3759. SourceLocation opLoc,
  3760. Expr *op) {
  3761. assert(op->getType()->isObjCObjectPointerType());
  3762. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3763. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3764. return false;
  3765. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3766. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3767. << op->getSourceRange();
  3768. return true;
  3769. }
  3770. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3771. auto *BaseNoParens = Base->IgnoreParens();
  3772. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3773. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3774. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3775. }
  3776. ExprResult
  3777. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3778. Expr *idx, SourceLocation rbLoc) {
  3779. if (base && !base->getType().isNull() &&
  3780. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3781. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3782. /*Length=*/nullptr, rbLoc);
  3783. // Since this might be a postfix expression, get rid of ParenListExprs.
  3784. if (isa<ParenListExpr>(base)) {
  3785. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3786. if (result.isInvalid()) return ExprError();
  3787. base = result.get();
  3788. }
  3789. // A comma-expression as the index is deprecated in C++2a onwards.
  3790. if (getLangOpts().CPlusPlus2a &&
  3791. ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
  3792. (isa<CXXOperatorCallExpr>(idx) &&
  3793. cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
  3794. Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
  3795. << SourceRange(base->getBeginLoc(), rbLoc);
  3796. }
  3797. // Handle any non-overload placeholder types in the base and index
  3798. // expressions. We can't handle overloads here because the other
  3799. // operand might be an overloadable type, in which case the overload
  3800. // resolution for the operator overload should get the first crack
  3801. // at the overload.
  3802. bool IsMSPropertySubscript = false;
  3803. if (base->getType()->isNonOverloadPlaceholderType()) {
  3804. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3805. if (!IsMSPropertySubscript) {
  3806. ExprResult result = CheckPlaceholderExpr(base);
  3807. if (result.isInvalid())
  3808. return ExprError();
  3809. base = result.get();
  3810. }
  3811. }
  3812. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3813. ExprResult result = CheckPlaceholderExpr(idx);
  3814. if (result.isInvalid()) return ExprError();
  3815. idx = result.get();
  3816. }
  3817. // Build an unanalyzed expression if either operand is type-dependent.
  3818. if (getLangOpts().CPlusPlus &&
  3819. (base->isTypeDependent() || idx->isTypeDependent())) {
  3820. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3821. VK_LValue, OK_Ordinary, rbLoc);
  3822. }
  3823. // MSDN, property (C++)
  3824. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3825. // This attribute can also be used in the declaration of an empty array in a
  3826. // class or structure definition. For example:
  3827. // __declspec(property(get=GetX, put=PutX)) int x[];
  3828. // The above statement indicates that x[] can be used with one or more array
  3829. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3830. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3831. if (IsMSPropertySubscript) {
  3832. // Build MS property subscript expression if base is MS property reference
  3833. // or MS property subscript.
  3834. return new (Context) MSPropertySubscriptExpr(
  3835. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3836. }
  3837. // Use C++ overloaded-operator rules if either operand has record
  3838. // type. The spec says to do this if either type is *overloadable*,
  3839. // but enum types can't declare subscript operators or conversion
  3840. // operators, so there's nothing interesting for overload resolution
  3841. // to do if there aren't any record types involved.
  3842. //
  3843. // ObjC pointers have their own subscripting logic that is not tied
  3844. // to overload resolution and so should not take this path.
  3845. if (getLangOpts().CPlusPlus &&
  3846. (base->getType()->isRecordType() ||
  3847. (!base->getType()->isObjCObjectPointerType() &&
  3848. idx->getType()->isRecordType()))) {
  3849. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3850. }
  3851. ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3852. if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
  3853. CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
  3854. return Res;
  3855. }
  3856. void Sema::CheckAddressOfNoDeref(const Expr *E) {
  3857. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3858. const Expr *StrippedExpr = E->IgnoreParenImpCasts();
  3859. // For expressions like `&(*s).b`, the base is recorded and what should be
  3860. // checked.
  3861. const MemberExpr *Member = nullptr;
  3862. while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
  3863. StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
  3864. LastRecord.PossibleDerefs.erase(StrippedExpr);
  3865. }
  3866. void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
  3867. QualType ResultTy = E->getType();
  3868. ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
  3869. // Bail if the element is an array since it is not memory access.
  3870. if (isa<ArrayType>(ResultTy))
  3871. return;
  3872. if (ResultTy->hasAttr(attr::NoDeref)) {
  3873. LastRecord.PossibleDerefs.insert(E);
  3874. return;
  3875. }
  3876. // Check if the base type is a pointer to a member access of a struct
  3877. // marked with noderef.
  3878. const Expr *Base = E->getBase();
  3879. QualType BaseTy = Base->getType();
  3880. if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
  3881. // Not a pointer access
  3882. return;
  3883. const MemberExpr *Member = nullptr;
  3884. while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
  3885. Member->isArrow())
  3886. Base = Member->getBase();
  3887. if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
  3888. if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
  3889. LastRecord.PossibleDerefs.insert(E);
  3890. }
  3891. }
  3892. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3893. Expr *LowerBound,
  3894. SourceLocation ColonLoc, Expr *Length,
  3895. SourceLocation RBLoc) {
  3896. if (Base->getType()->isPlaceholderType() &&
  3897. !Base->getType()->isSpecificPlaceholderType(
  3898. BuiltinType::OMPArraySection)) {
  3899. ExprResult Result = CheckPlaceholderExpr(Base);
  3900. if (Result.isInvalid())
  3901. return ExprError();
  3902. Base = Result.get();
  3903. }
  3904. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3905. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3906. if (Result.isInvalid())
  3907. return ExprError();
  3908. Result = DefaultLvalueConversion(Result.get());
  3909. if (Result.isInvalid())
  3910. return ExprError();
  3911. LowerBound = Result.get();
  3912. }
  3913. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3914. ExprResult Result = CheckPlaceholderExpr(Length);
  3915. if (Result.isInvalid())
  3916. return ExprError();
  3917. Result = DefaultLvalueConversion(Result.get());
  3918. if (Result.isInvalid())
  3919. return ExprError();
  3920. Length = Result.get();
  3921. }
  3922. // Build an unanalyzed expression if either operand is type-dependent.
  3923. if (Base->isTypeDependent() ||
  3924. (LowerBound &&
  3925. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3926. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3927. return new (Context)
  3928. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3929. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3930. }
  3931. // Perform default conversions.
  3932. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3933. QualType ResultTy;
  3934. if (OriginalTy->isAnyPointerType()) {
  3935. ResultTy = OriginalTy->getPointeeType();
  3936. } else if (OriginalTy->isArrayType()) {
  3937. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3938. } else {
  3939. return ExprError(
  3940. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3941. << Base->getSourceRange());
  3942. }
  3943. // C99 6.5.2.1p1
  3944. if (LowerBound) {
  3945. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3946. LowerBound);
  3947. if (Res.isInvalid())
  3948. return ExprError(Diag(LowerBound->getExprLoc(),
  3949. diag::err_omp_typecheck_section_not_integer)
  3950. << 0 << LowerBound->getSourceRange());
  3951. LowerBound = Res.get();
  3952. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3953. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3954. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3955. << 0 << LowerBound->getSourceRange();
  3956. }
  3957. if (Length) {
  3958. auto Res =
  3959. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3960. if (Res.isInvalid())
  3961. return ExprError(Diag(Length->getExprLoc(),
  3962. diag::err_omp_typecheck_section_not_integer)
  3963. << 1 << Length->getSourceRange());
  3964. Length = Res.get();
  3965. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3966. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3967. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3968. << 1 << Length->getSourceRange();
  3969. }
  3970. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3971. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3972. // type. Note that functions are not objects, and that (in C99 parlance)
  3973. // incomplete types are not object types.
  3974. if (ResultTy->isFunctionType()) {
  3975. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3976. << ResultTy << Base->getSourceRange();
  3977. return ExprError();
  3978. }
  3979. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3980. diag::err_omp_section_incomplete_type, Base))
  3981. return ExprError();
  3982. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3983. Expr::EvalResult Result;
  3984. if (LowerBound->EvaluateAsInt(Result, Context)) {
  3985. // OpenMP 4.5, [2.4 Array Sections]
  3986. // The array section must be a subset of the original array.
  3987. llvm::APSInt LowerBoundValue = Result.Val.getInt();
  3988. if (LowerBoundValue.isNegative()) {
  3989. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3990. << LowerBound->getSourceRange();
  3991. return ExprError();
  3992. }
  3993. }
  3994. }
  3995. if (Length) {
  3996. Expr::EvalResult Result;
  3997. if (Length->EvaluateAsInt(Result, Context)) {
  3998. // OpenMP 4.5, [2.4 Array Sections]
  3999. // The length must evaluate to non-negative integers.
  4000. llvm::APSInt LengthValue = Result.Val.getInt();
  4001. if (LengthValue.isNegative()) {
  4002. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  4003. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  4004. << Length->getSourceRange();
  4005. return ExprError();
  4006. }
  4007. }
  4008. } else if (ColonLoc.isValid() &&
  4009. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  4010. !OriginalTy->isVariableArrayType()))) {
  4011. // OpenMP 4.5, [2.4 Array Sections]
  4012. // When the size of the array dimension is not known, the length must be
  4013. // specified explicitly.
  4014. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  4015. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  4016. return ExprError();
  4017. }
  4018. if (!Base->getType()->isSpecificPlaceholderType(
  4019. BuiltinType::OMPArraySection)) {
  4020. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  4021. if (Result.isInvalid())
  4022. return ExprError();
  4023. Base = Result.get();
  4024. }
  4025. return new (Context)
  4026. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  4027. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  4028. }
  4029. ExprResult
  4030. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  4031. Expr *Idx, SourceLocation RLoc) {
  4032. Expr *LHSExp = Base;
  4033. Expr *RHSExp = Idx;
  4034. ExprValueKind VK = VK_LValue;
  4035. ExprObjectKind OK = OK_Ordinary;
  4036. // Per C++ core issue 1213, the result is an xvalue if either operand is
  4037. // a non-lvalue array, and an lvalue otherwise.
  4038. if (getLangOpts().CPlusPlus11) {
  4039. for (auto *Op : {LHSExp, RHSExp}) {
  4040. Op = Op->IgnoreImplicit();
  4041. if (Op->getType()->isArrayType() && !Op->isLValue())
  4042. VK = VK_XValue;
  4043. }
  4044. }
  4045. // Perform default conversions.
  4046. if (!LHSExp->getType()->getAs<VectorType>()) {
  4047. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  4048. if (Result.isInvalid())
  4049. return ExprError();
  4050. LHSExp = Result.get();
  4051. }
  4052. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  4053. if (Result.isInvalid())
  4054. return ExprError();
  4055. RHSExp = Result.get();
  4056. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  4057. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  4058. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  4059. // in the subscript position. As a result, we need to derive the array base
  4060. // and index from the expression types.
  4061. Expr *BaseExpr, *IndexExpr;
  4062. QualType ResultType;
  4063. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  4064. BaseExpr = LHSExp;
  4065. IndexExpr = RHSExp;
  4066. ResultType = Context.DependentTy;
  4067. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  4068. BaseExpr = LHSExp;
  4069. IndexExpr = RHSExp;
  4070. ResultType = PTy->getPointeeType();
  4071. } else if (const ObjCObjectPointerType *PTy =
  4072. LHSTy->getAs<ObjCObjectPointerType>()) {
  4073. BaseExpr = LHSExp;
  4074. IndexExpr = RHSExp;
  4075. // Use custom logic if this should be the pseudo-object subscript
  4076. // expression.
  4077. if (!LangOpts.isSubscriptPointerArithmetic())
  4078. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  4079. nullptr);
  4080. ResultType = PTy->getPointeeType();
  4081. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  4082. // Handle the uncommon case of "123[Ptr]".
  4083. BaseExpr = RHSExp;
  4084. IndexExpr = LHSExp;
  4085. ResultType = PTy->getPointeeType();
  4086. } else if (const ObjCObjectPointerType *PTy =
  4087. RHSTy->getAs<ObjCObjectPointerType>()) {
  4088. // Handle the uncommon case of "123[Ptr]".
  4089. BaseExpr = RHSExp;
  4090. IndexExpr = LHSExp;
  4091. ResultType = PTy->getPointeeType();
  4092. if (!LangOpts.isSubscriptPointerArithmetic()) {
  4093. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  4094. << ResultType << BaseExpr->getSourceRange();
  4095. return ExprError();
  4096. }
  4097. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  4098. BaseExpr = LHSExp; // vectors: V[123]
  4099. IndexExpr = RHSExp;
  4100. // We apply C++ DR1213 to vector subscripting too.
  4101. if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
  4102. ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
  4103. if (Materialized.isInvalid())
  4104. return ExprError();
  4105. LHSExp = Materialized.get();
  4106. }
  4107. VK = LHSExp->getValueKind();
  4108. if (VK != VK_RValue)
  4109. OK = OK_VectorComponent;
  4110. ResultType = VTy->getElementType();
  4111. QualType BaseType = BaseExpr->getType();
  4112. Qualifiers BaseQuals = BaseType.getQualifiers();
  4113. Qualifiers MemberQuals = ResultType.getQualifiers();
  4114. Qualifiers Combined = BaseQuals + MemberQuals;
  4115. if (Combined != MemberQuals)
  4116. ResultType = Context.getQualifiedType(ResultType, Combined);
  4117. } else if (LHSTy->isArrayType()) {
  4118. // If we see an array that wasn't promoted by
  4119. // DefaultFunctionArrayLvalueConversion, it must be an array that
  4120. // wasn't promoted because of the C90 rule that doesn't
  4121. // allow promoting non-lvalue arrays. Warn, then
  4122. // force the promotion here.
  4123. Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4124. << LHSExp->getSourceRange();
  4125. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  4126. CK_ArrayToPointerDecay).get();
  4127. LHSTy = LHSExp->getType();
  4128. BaseExpr = LHSExp;
  4129. IndexExpr = RHSExp;
  4130. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  4131. } else if (RHSTy->isArrayType()) {
  4132. // Same as previous, except for 123[f().a] case
  4133. Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
  4134. << RHSExp->getSourceRange();
  4135. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  4136. CK_ArrayToPointerDecay).get();
  4137. RHSTy = RHSExp->getType();
  4138. BaseExpr = RHSExp;
  4139. IndexExpr = LHSExp;
  4140. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  4141. } else {
  4142. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  4143. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  4144. }
  4145. // C99 6.5.2.1p1
  4146. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  4147. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  4148. << IndexExpr->getSourceRange());
  4149. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  4150. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  4151. && !IndexExpr->isTypeDependent())
  4152. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  4153. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  4154. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  4155. // type. Note that Functions are not objects, and that (in C99 parlance)
  4156. // incomplete types are not object types.
  4157. if (ResultType->isFunctionType()) {
  4158. Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
  4159. << ResultType << BaseExpr->getSourceRange();
  4160. return ExprError();
  4161. }
  4162. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  4163. // GNU extension: subscripting on pointer to void
  4164. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  4165. << BaseExpr->getSourceRange();
  4166. // C forbids expressions of unqualified void type from being l-values.
  4167. // See IsCForbiddenLValueType.
  4168. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  4169. } else if (!ResultType->isDependentType() &&
  4170. RequireCompleteType(LLoc, ResultType,
  4171. diag::err_subscript_incomplete_type, BaseExpr))
  4172. return ExprError();
  4173. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  4174. !ResultType.isCForbiddenLValueType());
  4175. if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
  4176. FunctionScopes.size() > 1) {
  4177. if (auto *TT =
  4178. LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
  4179. for (auto I = FunctionScopes.rbegin(),
  4180. E = std::prev(FunctionScopes.rend());
  4181. I != E; ++I) {
  4182. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  4183. if (CSI == nullptr)
  4184. break;
  4185. DeclContext *DC = nullptr;
  4186. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  4187. DC = LSI->CallOperator;
  4188. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  4189. DC = CRSI->TheCapturedDecl;
  4190. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  4191. DC = BSI->TheDecl;
  4192. if (DC) {
  4193. if (DC->containsDecl(TT->getDecl()))
  4194. break;
  4195. captureVariablyModifiedType(
  4196. Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
  4197. }
  4198. }
  4199. }
  4200. }
  4201. return new (Context)
  4202. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  4203. }
  4204. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  4205. ParmVarDecl *Param) {
  4206. if (Param->hasUnparsedDefaultArg()) {
  4207. Diag(CallLoc,
  4208. diag::err_use_of_default_argument_to_function_declared_later) <<
  4209. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  4210. Diag(UnparsedDefaultArgLocs[Param],
  4211. diag::note_default_argument_declared_here);
  4212. return true;
  4213. }
  4214. if (Param->hasUninstantiatedDefaultArg()) {
  4215. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  4216. EnterExpressionEvaluationContext EvalContext(
  4217. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4218. // Instantiate the expression.
  4219. //
  4220. // FIXME: Pass in a correct Pattern argument, otherwise
  4221. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  4222. //
  4223. // template<typename T>
  4224. // struct A {
  4225. // static int FooImpl();
  4226. //
  4227. // template<typename Tp>
  4228. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  4229. // // template argument list [[T], [Tp]], should be [[Tp]].
  4230. // friend A<Tp> Foo(int a);
  4231. // };
  4232. //
  4233. // template<typename T>
  4234. // A<T> Foo(int a = A<T>::FooImpl());
  4235. MultiLevelTemplateArgumentList MutiLevelArgList
  4236. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  4237. InstantiatingTemplate Inst(*this, CallLoc, Param,
  4238. MutiLevelArgList.getInnermost());
  4239. if (Inst.isInvalid())
  4240. return true;
  4241. if (Inst.isAlreadyInstantiating()) {
  4242. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4243. Param->setInvalidDecl();
  4244. return true;
  4245. }
  4246. ExprResult Result;
  4247. {
  4248. // C++ [dcl.fct.default]p5:
  4249. // The names in the [default argument] expression are bound, and
  4250. // the semantic constraints are checked, at the point where the
  4251. // default argument expression appears.
  4252. ContextRAII SavedContext(*this, FD);
  4253. LocalInstantiationScope Local(*this);
  4254. runWithSufficientStackSpace(CallLoc, [&] {
  4255. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  4256. /*DirectInit*/false);
  4257. });
  4258. }
  4259. if (Result.isInvalid())
  4260. return true;
  4261. // Check the expression as an initializer for the parameter.
  4262. InitializedEntity Entity
  4263. = InitializedEntity::InitializeParameter(Context, Param);
  4264. InitializationKind Kind = InitializationKind::CreateCopy(
  4265. Param->getLocation(),
  4266. /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
  4267. Expr *ResultE = Result.getAs<Expr>();
  4268. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  4269. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  4270. if (Result.isInvalid())
  4271. return true;
  4272. Result =
  4273. ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
  4274. /*DiscardedValue*/ false);
  4275. if (Result.isInvalid())
  4276. return true;
  4277. // Remember the instantiated default argument.
  4278. Param->setDefaultArg(Result.getAs<Expr>());
  4279. if (ASTMutationListener *L = getASTMutationListener()) {
  4280. L->DefaultArgumentInstantiated(Param);
  4281. }
  4282. }
  4283. // If the default argument expression is not set yet, we are building it now.
  4284. if (!Param->hasInit()) {
  4285. Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
  4286. Param->setInvalidDecl();
  4287. return true;
  4288. }
  4289. // If the default expression creates temporaries, we need to
  4290. // push them to the current stack of expression temporaries so they'll
  4291. // be properly destroyed.
  4292. // FIXME: We should really be rebuilding the default argument with new
  4293. // bound temporaries; see the comment in PR5810.
  4294. // We don't need to do that with block decls, though, because
  4295. // blocks in default argument expression can never capture anything.
  4296. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4297. // Set the "needs cleanups" bit regardless of whether there are
  4298. // any explicit objects.
  4299. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4300. // Append all the objects to the cleanup list. Right now, this
  4301. // should always be a no-op, because blocks in default argument
  4302. // expressions should never be able to capture anything.
  4303. assert(!Init->getNumObjects() &&
  4304. "default argument expression has capturing blocks?");
  4305. }
  4306. // We already type-checked the argument, so we know it works.
  4307. // Just mark all of the declarations in this potentially-evaluated expression
  4308. // as being "referenced".
  4309. EnterExpressionEvaluationContext EvalContext(
  4310. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  4311. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4312. /*SkipLocalVariables=*/true);
  4313. return false;
  4314. }
  4315. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4316. FunctionDecl *FD, ParmVarDecl *Param) {
  4317. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4318. return ExprError();
  4319. return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
  4320. }
  4321. Sema::VariadicCallType
  4322. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4323. Expr *Fn) {
  4324. if (Proto && Proto->isVariadic()) {
  4325. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4326. return VariadicConstructor;
  4327. else if (Fn && Fn->getType()->isBlockPointerType())
  4328. return VariadicBlock;
  4329. else if (FDecl) {
  4330. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4331. if (Method->isInstance())
  4332. return VariadicMethod;
  4333. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4334. return VariadicMethod;
  4335. return VariadicFunction;
  4336. }
  4337. return VariadicDoesNotApply;
  4338. }
  4339. namespace {
  4340. class FunctionCallCCC final : public FunctionCallFilterCCC {
  4341. public:
  4342. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4343. unsigned NumArgs, MemberExpr *ME)
  4344. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4345. FunctionName(FuncName) {}
  4346. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4347. if (!candidate.getCorrectionSpecifier() ||
  4348. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4349. return false;
  4350. }
  4351. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4352. }
  4353. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  4354. return std::make_unique<FunctionCallCCC>(*this);
  4355. }
  4356. private:
  4357. const IdentifierInfo *const FunctionName;
  4358. };
  4359. }
  4360. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4361. FunctionDecl *FDecl,
  4362. ArrayRef<Expr *> Args) {
  4363. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4364. DeclarationName FuncName = FDecl->getDeclName();
  4365. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
  4366. FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
  4367. if (TypoCorrection Corrected = S.CorrectTypo(
  4368. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4369. S.getScopeForContext(S.CurContext), nullptr, CCC,
  4370. Sema::CTK_ErrorRecovery)) {
  4371. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4372. if (Corrected.isOverloaded()) {
  4373. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4374. OverloadCandidateSet::iterator Best;
  4375. for (NamedDecl *CD : Corrected) {
  4376. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4377. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4378. OCS);
  4379. }
  4380. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4381. case OR_Success:
  4382. ND = Best->FoundDecl;
  4383. Corrected.setCorrectionDecl(ND);
  4384. break;
  4385. default:
  4386. break;
  4387. }
  4388. }
  4389. ND = ND->getUnderlyingDecl();
  4390. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4391. return Corrected;
  4392. }
  4393. }
  4394. return TypoCorrection();
  4395. }
  4396. /// ConvertArgumentsForCall - Converts the arguments specified in
  4397. /// Args/NumArgs to the parameter types of the function FDecl with
  4398. /// function prototype Proto. Call is the call expression itself, and
  4399. /// Fn is the function expression. For a C++ member function, this
  4400. /// routine does not attempt to convert the object argument. Returns
  4401. /// true if the call is ill-formed.
  4402. bool
  4403. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4404. FunctionDecl *FDecl,
  4405. const FunctionProtoType *Proto,
  4406. ArrayRef<Expr *> Args,
  4407. SourceLocation RParenLoc,
  4408. bool IsExecConfig) {
  4409. // Bail out early if calling a builtin with custom typechecking.
  4410. if (FDecl)
  4411. if (unsigned ID = FDecl->getBuiltinID())
  4412. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4413. return false;
  4414. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4415. // assignment, to the types of the corresponding parameter, ...
  4416. unsigned NumParams = Proto->getNumParams();
  4417. bool Invalid = false;
  4418. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4419. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4420. ? 1 /* block */
  4421. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4422. : 0 /* function */);
  4423. // If too few arguments are available (and we don't have default
  4424. // arguments for the remaining parameters), don't make the call.
  4425. if (Args.size() < NumParams) {
  4426. if (Args.size() < MinArgs) {
  4427. TypoCorrection TC;
  4428. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4429. unsigned diag_id =
  4430. MinArgs == NumParams && !Proto->isVariadic()
  4431. ? diag::err_typecheck_call_too_few_args_suggest
  4432. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4433. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4434. << static_cast<unsigned>(Args.size())
  4435. << TC.getCorrectionRange());
  4436. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4437. Diag(RParenLoc,
  4438. MinArgs == NumParams && !Proto->isVariadic()
  4439. ? diag::err_typecheck_call_too_few_args_one
  4440. : diag::err_typecheck_call_too_few_args_at_least_one)
  4441. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4442. else
  4443. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4444. ? diag::err_typecheck_call_too_few_args
  4445. : diag::err_typecheck_call_too_few_args_at_least)
  4446. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4447. << Fn->getSourceRange();
  4448. // Emit the location of the prototype.
  4449. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4450. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4451. return true;
  4452. }
  4453. // We reserve space for the default arguments when we create
  4454. // the call expression, before calling ConvertArgumentsForCall.
  4455. assert((Call->getNumArgs() == NumParams) &&
  4456. "We should have reserved space for the default arguments before!");
  4457. }
  4458. // If too many are passed and not variadic, error on the extras and drop
  4459. // them.
  4460. if (Args.size() > NumParams) {
  4461. if (!Proto->isVariadic()) {
  4462. TypoCorrection TC;
  4463. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4464. unsigned diag_id =
  4465. MinArgs == NumParams && !Proto->isVariadic()
  4466. ? diag::err_typecheck_call_too_many_args_suggest
  4467. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4468. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4469. << static_cast<unsigned>(Args.size())
  4470. << TC.getCorrectionRange());
  4471. } else if (NumParams == 1 && FDecl &&
  4472. FDecl->getParamDecl(0)->getDeclName())
  4473. Diag(Args[NumParams]->getBeginLoc(),
  4474. MinArgs == NumParams
  4475. ? diag::err_typecheck_call_too_many_args_one
  4476. : diag::err_typecheck_call_too_many_args_at_most_one)
  4477. << FnKind << FDecl->getParamDecl(0)
  4478. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4479. << SourceRange(Args[NumParams]->getBeginLoc(),
  4480. Args.back()->getEndLoc());
  4481. else
  4482. Diag(Args[NumParams]->getBeginLoc(),
  4483. MinArgs == NumParams
  4484. ? diag::err_typecheck_call_too_many_args
  4485. : diag::err_typecheck_call_too_many_args_at_most)
  4486. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4487. << Fn->getSourceRange()
  4488. << SourceRange(Args[NumParams]->getBeginLoc(),
  4489. Args.back()->getEndLoc());
  4490. // Emit the location of the prototype.
  4491. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4492. Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
  4493. // This deletes the extra arguments.
  4494. Call->shrinkNumArgs(NumParams);
  4495. return true;
  4496. }
  4497. }
  4498. SmallVector<Expr *, 8> AllArgs;
  4499. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4500. Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
  4501. AllArgs, CallType);
  4502. if (Invalid)
  4503. return true;
  4504. unsigned TotalNumArgs = AllArgs.size();
  4505. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4506. Call->setArg(i, AllArgs[i]);
  4507. return false;
  4508. }
  4509. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4510. const FunctionProtoType *Proto,
  4511. unsigned FirstParam, ArrayRef<Expr *> Args,
  4512. SmallVectorImpl<Expr *> &AllArgs,
  4513. VariadicCallType CallType, bool AllowExplicit,
  4514. bool IsListInitialization) {
  4515. unsigned NumParams = Proto->getNumParams();
  4516. bool Invalid = false;
  4517. size_t ArgIx = 0;
  4518. // Continue to check argument types (even if we have too few/many args).
  4519. for (unsigned i = FirstParam; i < NumParams; i++) {
  4520. QualType ProtoArgType = Proto->getParamType(i);
  4521. Expr *Arg;
  4522. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4523. if (ArgIx < Args.size()) {
  4524. Arg = Args[ArgIx++];
  4525. if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
  4526. diag::err_call_incomplete_argument, Arg))
  4527. return true;
  4528. // Strip the unbridged-cast placeholder expression off, if applicable.
  4529. bool CFAudited = false;
  4530. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4531. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4532. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4533. Arg = stripARCUnbridgedCast(Arg);
  4534. else if (getLangOpts().ObjCAutoRefCount &&
  4535. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4536. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4537. CFAudited = true;
  4538. if (Proto->getExtParameterInfo(i).isNoEscape())
  4539. if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
  4540. BE->getBlockDecl()->setDoesNotEscape();
  4541. InitializedEntity Entity =
  4542. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4543. ProtoArgType)
  4544. : InitializedEntity::InitializeParameter(
  4545. Context, ProtoArgType, Proto->isParamConsumed(i));
  4546. // Remember that parameter belongs to a CF audited API.
  4547. if (CFAudited)
  4548. Entity.setParameterCFAudited();
  4549. ExprResult ArgE = PerformCopyInitialization(
  4550. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4551. if (ArgE.isInvalid())
  4552. return true;
  4553. Arg = ArgE.getAs<Expr>();
  4554. } else {
  4555. assert(Param && "can't use default arguments without a known callee");
  4556. ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4557. if (ArgExpr.isInvalid())
  4558. return true;
  4559. Arg = ArgExpr.getAs<Expr>();
  4560. }
  4561. // Check for array bounds violations for each argument to the call. This
  4562. // check only triggers warnings when the argument isn't a more complex Expr
  4563. // with its own checking, such as a BinaryOperator.
  4564. CheckArrayAccess(Arg);
  4565. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4566. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4567. AllArgs.push_back(Arg);
  4568. }
  4569. // If this is a variadic call, handle args passed through "...".
  4570. if (CallType != VariadicDoesNotApply) {
  4571. // Assume that extern "C" functions with variadic arguments that
  4572. // return __unknown_anytype aren't *really* variadic.
  4573. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4574. FDecl->isExternC()) {
  4575. for (Expr *A : Args.slice(ArgIx)) {
  4576. QualType paramType; // ignored
  4577. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4578. Invalid |= arg.isInvalid();
  4579. AllArgs.push_back(arg.get());
  4580. }
  4581. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4582. } else {
  4583. for (Expr *A : Args.slice(ArgIx)) {
  4584. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4585. Invalid |= Arg.isInvalid();
  4586. AllArgs.push_back(Arg.get());
  4587. }
  4588. }
  4589. // Check for array bounds violations.
  4590. for (Expr *A : Args.slice(ArgIx))
  4591. CheckArrayAccess(A);
  4592. }
  4593. return Invalid;
  4594. }
  4595. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4596. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4597. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4598. TL = DTL.getOriginalLoc();
  4599. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4600. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4601. << ATL.getLocalSourceRange();
  4602. }
  4603. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4604. /// array parameter, check that it is non-null, and that if it is formed by
  4605. /// array-to-pointer decay, the underlying array is sufficiently large.
  4606. ///
  4607. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4608. /// array type derivation, then for each call to the function, the value of the
  4609. /// corresponding actual argument shall provide access to the first element of
  4610. /// an array with at least as many elements as specified by the size expression.
  4611. void
  4612. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4613. ParmVarDecl *Param,
  4614. const Expr *ArgExpr) {
  4615. // Static array parameters are not supported in C++.
  4616. if (!Param || getLangOpts().CPlusPlus)
  4617. return;
  4618. QualType OrigTy = Param->getOriginalType();
  4619. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4620. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4621. return;
  4622. if (ArgExpr->isNullPointerConstant(Context,
  4623. Expr::NPC_NeverValueDependent)) {
  4624. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4625. DiagnoseCalleeStaticArrayParam(*this, Param);
  4626. return;
  4627. }
  4628. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4629. if (!CAT)
  4630. return;
  4631. const ConstantArrayType *ArgCAT =
  4632. Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
  4633. if (!ArgCAT)
  4634. return;
  4635. if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
  4636. ArgCAT->getElementType())) {
  4637. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4638. Diag(CallLoc, diag::warn_static_array_too_small)
  4639. << ArgExpr->getSourceRange()
  4640. << (unsigned)ArgCAT->getSize().getZExtValue()
  4641. << (unsigned)CAT->getSize().getZExtValue() << 0;
  4642. DiagnoseCalleeStaticArrayParam(*this, Param);
  4643. }
  4644. return;
  4645. }
  4646. Optional<CharUnits> ArgSize =
  4647. getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
  4648. Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
  4649. if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
  4650. Diag(CallLoc, diag::warn_static_array_too_small)
  4651. << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
  4652. << (unsigned)ParmSize->getQuantity() << 1;
  4653. DiagnoseCalleeStaticArrayParam(*this, Param);
  4654. }
  4655. }
  4656. /// Given a function expression of unknown-any type, try to rebuild it
  4657. /// to have a function type.
  4658. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4659. /// Is the given type a placeholder that we need to lower out
  4660. /// immediately during argument processing?
  4661. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4662. // Placeholders are never sugared.
  4663. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4664. if (!placeholder) return false;
  4665. switch (placeholder->getKind()) {
  4666. // Ignore all the non-placeholder types.
  4667. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4668. case BuiltinType::Id:
  4669. #include "clang/Basic/OpenCLImageTypes.def"
  4670. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  4671. case BuiltinType::Id:
  4672. #include "clang/Basic/OpenCLExtensionTypes.def"
  4673. // In practice we'll never use this, since all SVE types are sugared
  4674. // via TypedefTypes rather than exposed directly as BuiltinTypes.
  4675. #define SVE_TYPE(Name, Id, SingletonId) \
  4676. case BuiltinType::Id:
  4677. #include "clang/Basic/AArch64SVEACLETypes.def"
  4678. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4679. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4680. #include "clang/AST/BuiltinTypes.def"
  4681. return false;
  4682. // We cannot lower out overload sets; they might validly be resolved
  4683. // by the call machinery.
  4684. case BuiltinType::Overload:
  4685. return false;
  4686. // Unbridged casts in ARC can be handled in some call positions and
  4687. // should be left in place.
  4688. case BuiltinType::ARCUnbridgedCast:
  4689. return false;
  4690. // Pseudo-objects should be converted as soon as possible.
  4691. case BuiltinType::PseudoObject:
  4692. return true;
  4693. // The debugger mode could theoretically but currently does not try
  4694. // to resolve unknown-typed arguments based on known parameter types.
  4695. case BuiltinType::UnknownAny:
  4696. return true;
  4697. // These are always invalid as call arguments and should be reported.
  4698. case BuiltinType::BoundMember:
  4699. case BuiltinType::BuiltinFn:
  4700. case BuiltinType::OMPArraySection:
  4701. return true;
  4702. }
  4703. llvm_unreachable("bad builtin type kind");
  4704. }
  4705. /// Check an argument list for placeholders that we won't try to
  4706. /// handle later.
  4707. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4708. // Apply this processing to all the arguments at once instead of
  4709. // dying at the first failure.
  4710. bool hasInvalid = false;
  4711. for (size_t i = 0, e = args.size(); i != e; i++) {
  4712. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4713. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4714. if (result.isInvalid()) hasInvalid = true;
  4715. else args[i] = result.get();
  4716. } else if (hasInvalid) {
  4717. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4718. }
  4719. }
  4720. return hasInvalid;
  4721. }
  4722. /// If a builtin function has a pointer argument with no explicit address
  4723. /// space, then it should be able to accept a pointer to any address
  4724. /// space as input. In order to do this, we need to replace the
  4725. /// standard builtin declaration with one that uses the same address space
  4726. /// as the call.
  4727. ///
  4728. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4729. /// it does not contain any pointer arguments without
  4730. /// an address space qualifer. Otherwise the rewritten
  4731. /// FunctionDecl is returned.
  4732. /// TODO: Handle pointer return types.
  4733. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4734. FunctionDecl *FDecl,
  4735. MultiExprArg ArgExprs) {
  4736. QualType DeclType = FDecl->getType();
  4737. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4738. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
  4739. ArgExprs.size() < FT->getNumParams())
  4740. return nullptr;
  4741. bool NeedsNewDecl = false;
  4742. unsigned i = 0;
  4743. SmallVector<QualType, 8> OverloadParams;
  4744. for (QualType ParamType : FT->param_types()) {
  4745. // Convert array arguments to pointer to simplify type lookup.
  4746. ExprResult ArgRes =
  4747. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4748. if (ArgRes.isInvalid())
  4749. return nullptr;
  4750. Expr *Arg = ArgRes.get();
  4751. QualType ArgType = Arg->getType();
  4752. if (!ParamType->isPointerType() ||
  4753. ParamType.getQualifiers().hasAddressSpace() ||
  4754. !ArgType->isPointerType() ||
  4755. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4756. OverloadParams.push_back(ParamType);
  4757. continue;
  4758. }
  4759. QualType PointeeType = ParamType->getPointeeType();
  4760. if (PointeeType.getQualifiers().hasAddressSpace())
  4761. continue;
  4762. NeedsNewDecl = true;
  4763. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4764. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4765. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4766. }
  4767. if (!NeedsNewDecl)
  4768. return nullptr;
  4769. FunctionProtoType::ExtProtoInfo EPI;
  4770. EPI.Variadic = FT->isVariadic();
  4771. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4772. OverloadParams, EPI);
  4773. DeclContext *Parent = FDecl->getParent();
  4774. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4775. FDecl->getLocation(),
  4776. FDecl->getLocation(),
  4777. FDecl->getIdentifier(),
  4778. OverloadTy,
  4779. /*TInfo=*/nullptr,
  4780. SC_Extern, false,
  4781. /*hasPrototype=*/true);
  4782. SmallVector<ParmVarDecl*, 16> Params;
  4783. FT = cast<FunctionProtoType>(OverloadTy);
  4784. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4785. QualType ParamType = FT->getParamType(i);
  4786. ParmVarDecl *Parm =
  4787. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4788. SourceLocation(), nullptr, ParamType,
  4789. /*TInfo=*/nullptr, SC_None, nullptr);
  4790. Parm->setScopeInfo(0, i);
  4791. Params.push_back(Parm);
  4792. }
  4793. OverloadDecl->setParams(Params);
  4794. return OverloadDecl;
  4795. }
  4796. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4797. FunctionDecl *Callee,
  4798. MultiExprArg ArgExprs) {
  4799. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4800. // similar attributes) really don't like it when functions are called with an
  4801. // invalid number of args.
  4802. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4803. /*PartialOverloading=*/false) &&
  4804. !Callee->isVariadic())
  4805. return;
  4806. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4807. return;
  4808. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4809. S.Diag(Fn->getBeginLoc(),
  4810. isa<CXXMethodDecl>(Callee)
  4811. ? diag::err_ovl_no_viable_member_function_in_call
  4812. : diag::err_ovl_no_viable_function_in_call)
  4813. << Callee << Callee->getSourceRange();
  4814. S.Diag(Callee->getLocation(),
  4815. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4816. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4817. return;
  4818. }
  4819. }
  4820. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4821. const UnresolvedMemberExpr *const UME, Sema &S) {
  4822. const auto GetFunctionLevelDCIfCXXClass =
  4823. [](Sema &S) -> const CXXRecordDecl * {
  4824. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4825. if (!DC || !DC->getParent())
  4826. return nullptr;
  4827. // If the call to some member function was made from within a member
  4828. // function body 'M' return return 'M's parent.
  4829. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4830. return MD->getParent()->getCanonicalDecl();
  4831. // else the call was made from within a default member initializer of a
  4832. // class, so return the class.
  4833. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4834. return RD->getCanonicalDecl();
  4835. return nullptr;
  4836. };
  4837. // If our DeclContext is neither a member function nor a class (in the
  4838. // case of a lambda in a default member initializer), we can't have an
  4839. // enclosing 'this'.
  4840. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4841. if (!CurParentClass)
  4842. return false;
  4843. // The naming class for implicit member functions call is the class in which
  4844. // name lookup starts.
  4845. const CXXRecordDecl *const NamingClass =
  4846. UME->getNamingClass()->getCanonicalDecl();
  4847. assert(NamingClass && "Must have naming class even for implicit access");
  4848. // If the unresolved member functions were found in a 'naming class' that is
  4849. // related (either the same or derived from) to the class that contains the
  4850. // member function that itself contained the implicit member access.
  4851. return CurParentClass == NamingClass ||
  4852. CurParentClass->isDerivedFrom(NamingClass);
  4853. }
  4854. static void
  4855. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4856. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4857. if (!UME)
  4858. return;
  4859. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4860. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4861. // already been captured, or if this is an implicit member function call (if
  4862. // it isn't, an attempt to capture 'this' should already have been made).
  4863. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4864. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4865. return;
  4866. // Check if the naming class in which the unresolved members were found is
  4867. // related (same as or is a base of) to the enclosing class.
  4868. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4869. return;
  4870. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4871. // If the enclosing function is not dependent, then this lambda is
  4872. // capture ready, so if we can capture this, do so.
  4873. if (!EnclosingFunctionCtx->isDependentContext()) {
  4874. // If the current lambda and all enclosing lambdas can capture 'this' -
  4875. // then go ahead and capture 'this' (since our unresolved overload set
  4876. // contains at least one non-static member function).
  4877. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4878. S.CheckCXXThisCapture(CallLoc);
  4879. } else if (S.CurContext->isDependentContext()) {
  4880. // ... since this is an implicit member reference, that might potentially
  4881. // involve a 'this' capture, mark 'this' for potential capture in
  4882. // enclosing lambdas.
  4883. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4884. CurLSI->addPotentialThisCapture(CallLoc);
  4885. }
  4886. }
  4887. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4888. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4889. Expr *ExecConfig) {
  4890. ExprResult Call =
  4891. BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
  4892. if (Call.isInvalid())
  4893. return Call;
  4894. // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
  4895. // language modes.
  4896. if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
  4897. if (ULE->hasExplicitTemplateArgs() &&
  4898. ULE->decls_begin() == ULE->decls_end()) {
  4899. Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
  4900. ? diag::warn_cxx17_compat_adl_only_template_id
  4901. : diag::ext_adl_only_template_id)
  4902. << ULE->getName();
  4903. }
  4904. }
  4905. return Call;
  4906. }
  4907. /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
  4908. /// This provides the location of the left/right parens and a list of comma
  4909. /// locations.
  4910. ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4911. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4912. Expr *ExecConfig, bool IsExecConfig) {
  4913. // Since this might be a postfix expression, get rid of ParenListExprs.
  4914. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4915. if (Result.isInvalid()) return ExprError();
  4916. Fn = Result.get();
  4917. if (checkArgsForPlaceholders(*this, ArgExprs))
  4918. return ExprError();
  4919. if (getLangOpts().CPlusPlus) {
  4920. // If this is a pseudo-destructor expression, build the call immediately.
  4921. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4922. if (!ArgExprs.empty()) {
  4923. // Pseudo-destructor calls should not have any arguments.
  4924. Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
  4925. << FixItHint::CreateRemoval(
  4926. SourceRange(ArgExprs.front()->getBeginLoc(),
  4927. ArgExprs.back()->getEndLoc()));
  4928. }
  4929. return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
  4930. VK_RValue, RParenLoc);
  4931. }
  4932. if (Fn->getType() == Context.PseudoObjectTy) {
  4933. ExprResult result = CheckPlaceholderExpr(Fn);
  4934. if (result.isInvalid()) return ExprError();
  4935. Fn = result.get();
  4936. }
  4937. // Determine whether this is a dependent call inside a C++ template,
  4938. // in which case we won't do any semantic analysis now.
  4939. if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
  4940. if (ExecConfig) {
  4941. return CUDAKernelCallExpr::Create(
  4942. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4943. Context.DependentTy, VK_RValue, RParenLoc);
  4944. } else {
  4945. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4946. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4947. Fn->getBeginLoc());
  4948. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4949. VK_RValue, RParenLoc);
  4950. }
  4951. }
  4952. // Determine whether this is a call to an object (C++ [over.call.object]).
  4953. if (Fn->getType()->isRecordType())
  4954. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4955. RParenLoc);
  4956. if (Fn->getType() == Context.UnknownAnyTy) {
  4957. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4958. if (result.isInvalid()) return ExprError();
  4959. Fn = result.get();
  4960. }
  4961. if (Fn->getType() == Context.BoundMemberTy) {
  4962. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4963. RParenLoc);
  4964. }
  4965. }
  4966. // Check for overloaded calls. This can happen even in C due to extensions.
  4967. if (Fn->getType() == Context.OverloadTy) {
  4968. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4969. // We aren't supposed to apply this logic if there's an '&' involved.
  4970. if (!find.HasFormOfMemberPointer) {
  4971. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4972. return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
  4973. VK_RValue, RParenLoc);
  4974. OverloadExpr *ovl = find.Expression;
  4975. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4976. return BuildOverloadedCallExpr(
  4977. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4978. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4979. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4980. RParenLoc);
  4981. }
  4982. }
  4983. // If we're directly calling a function, get the appropriate declaration.
  4984. if (Fn->getType() == Context.UnknownAnyTy) {
  4985. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4986. if (result.isInvalid()) return ExprError();
  4987. Fn = result.get();
  4988. }
  4989. Expr *NakedFn = Fn->IgnoreParens();
  4990. bool CallingNDeclIndirectly = false;
  4991. NamedDecl *NDecl = nullptr;
  4992. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4993. if (UnOp->getOpcode() == UO_AddrOf) {
  4994. CallingNDeclIndirectly = true;
  4995. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4996. }
  4997. }
  4998. if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  4999. NDecl = DRE->getDecl();
  5000. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  5001. if (FDecl && FDecl->getBuiltinID()) {
  5002. // Rewrite the function decl for this builtin by replacing parameters
  5003. // with no explicit address space with the address space of the arguments
  5004. // in ArgExprs.
  5005. if ((FDecl =
  5006. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  5007. NDecl = FDecl;
  5008. Fn = DeclRefExpr::Create(
  5009. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  5010. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
  5011. nullptr, DRE->isNonOdrUse());
  5012. }
  5013. }
  5014. } else if (isa<MemberExpr>(NakedFn))
  5015. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  5016. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  5017. if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
  5018. FD, /*Complain=*/true, Fn->getBeginLoc()))
  5019. return ExprError();
  5020. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  5021. return ExprError();
  5022. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  5023. }
  5024. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  5025. ExecConfig, IsExecConfig);
  5026. }
  5027. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  5028. ///
  5029. /// __builtin_astype( value, dst type )
  5030. ///
  5031. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  5032. SourceLocation BuiltinLoc,
  5033. SourceLocation RParenLoc) {
  5034. ExprValueKind VK = VK_RValue;
  5035. ExprObjectKind OK = OK_Ordinary;
  5036. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  5037. QualType SrcTy = E->getType();
  5038. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  5039. return ExprError(Diag(BuiltinLoc,
  5040. diag::err_invalid_astype_of_different_size)
  5041. << DstTy
  5042. << SrcTy
  5043. << E->getSourceRange());
  5044. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  5045. }
  5046. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  5047. /// provided arguments.
  5048. ///
  5049. /// __builtin_convertvector( value, dst type )
  5050. ///
  5051. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  5052. SourceLocation BuiltinLoc,
  5053. SourceLocation RParenLoc) {
  5054. TypeSourceInfo *TInfo;
  5055. GetTypeFromParser(ParsedDestTy, &TInfo);
  5056. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  5057. }
  5058. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  5059. /// i.e. an expression not of \p OverloadTy. The expression should
  5060. /// unary-convert to an expression of function-pointer or
  5061. /// block-pointer type.
  5062. ///
  5063. /// \param NDecl the declaration being called, if available
  5064. ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  5065. SourceLocation LParenLoc,
  5066. ArrayRef<Expr *> Args,
  5067. SourceLocation RParenLoc, Expr *Config,
  5068. bool IsExecConfig, ADLCallKind UsesADL) {
  5069. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  5070. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  5071. // Functions with 'interrupt' attribute cannot be called directly.
  5072. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  5073. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  5074. return ExprError();
  5075. }
  5076. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  5077. // so there's some risk when calling out to non-interrupt handler functions
  5078. // that the callee might not preserve them. This is easy to diagnose here,
  5079. // but can be very challenging to debug.
  5080. if (auto *Caller = getCurFunctionDecl())
  5081. if (Caller->hasAttr<ARMInterruptAttr>()) {
  5082. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  5083. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  5084. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  5085. }
  5086. // Promote the function operand.
  5087. // We special-case function promotion here because we only allow promoting
  5088. // builtin functions to function pointers in the callee of a call.
  5089. ExprResult Result;
  5090. QualType ResultTy;
  5091. if (BuiltinID &&
  5092. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  5093. // Extract the return type from the (builtin) function pointer type.
  5094. // FIXME Several builtins still have setType in
  5095. // Sema::CheckBuiltinFunctionCall. One should review their definitions in
  5096. // Builtins.def to ensure they are correct before removing setType calls.
  5097. QualType FnPtrTy = Context.getPointerType(FDecl->getType());
  5098. Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
  5099. ResultTy = FDecl->getCallResultType();
  5100. } else {
  5101. Result = CallExprUnaryConversions(Fn);
  5102. ResultTy = Context.BoolTy;
  5103. }
  5104. if (Result.isInvalid())
  5105. return ExprError();
  5106. Fn = Result.get();
  5107. // Check for a valid function type, but only if it is not a builtin which
  5108. // requires custom type checking. These will be handled by
  5109. // CheckBuiltinFunctionCall below just after creation of the call expression.
  5110. const FunctionType *FuncT = nullptr;
  5111. if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
  5112. retry:
  5113. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  5114. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  5115. // have type pointer to function".
  5116. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  5117. if (!FuncT)
  5118. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5119. << Fn->getType() << Fn->getSourceRange());
  5120. } else if (const BlockPointerType *BPT =
  5121. Fn->getType()->getAs<BlockPointerType>()) {
  5122. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  5123. } else {
  5124. // Handle calls to expressions of unknown-any type.
  5125. if (Fn->getType() == Context.UnknownAnyTy) {
  5126. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  5127. if (rewrite.isInvalid())
  5128. return ExprError();
  5129. Fn = rewrite.get();
  5130. goto retry;
  5131. }
  5132. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  5133. << Fn->getType() << Fn->getSourceRange());
  5134. }
  5135. }
  5136. // Get the number of parameters in the function prototype, if any.
  5137. // We will allocate space for max(Args.size(), NumParams) arguments
  5138. // in the call expression.
  5139. const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
  5140. unsigned NumParams = Proto ? Proto->getNumParams() : 0;
  5141. CallExpr *TheCall;
  5142. if (Config) {
  5143. assert(UsesADL == ADLCallKind::NotADL &&
  5144. "CUDAKernelCallExpr should not use ADL");
  5145. TheCall =
  5146. CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
  5147. ResultTy, VK_RValue, RParenLoc, NumParams);
  5148. } else {
  5149. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5150. RParenLoc, NumParams, UsesADL);
  5151. }
  5152. if (!getLangOpts().CPlusPlus) {
  5153. // Forget about the nulled arguments since typo correction
  5154. // do not handle them well.
  5155. TheCall->shrinkNumArgs(Args.size());
  5156. // C cannot always handle TypoExpr nodes in builtin calls and direct
  5157. // function calls as their argument checking don't necessarily handle
  5158. // dependent types properly, so make sure any TypoExprs have been
  5159. // dealt with.
  5160. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  5161. if (!Result.isUsable()) return ExprError();
  5162. CallExpr *TheOldCall = TheCall;
  5163. TheCall = dyn_cast<CallExpr>(Result.get());
  5164. bool CorrectedTypos = TheCall != TheOldCall;
  5165. if (!TheCall) return Result;
  5166. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  5167. // A new call expression node was created if some typos were corrected.
  5168. // However it may not have been constructed with enough storage. In this
  5169. // case, rebuild the node with enough storage. The waste of space is
  5170. // immaterial since this only happens when some typos were corrected.
  5171. if (CorrectedTypos && Args.size() < NumParams) {
  5172. if (Config)
  5173. TheCall = CUDAKernelCallExpr::Create(
  5174. Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
  5175. RParenLoc, NumParams);
  5176. else
  5177. TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
  5178. RParenLoc, NumParams, UsesADL);
  5179. }
  5180. // We can now handle the nulled arguments for the default arguments.
  5181. TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
  5182. }
  5183. // Bail out early if calling a builtin with custom type checking.
  5184. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  5185. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5186. if (getLangOpts().CUDA) {
  5187. if (Config) {
  5188. // CUDA: Kernel calls must be to global functions
  5189. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  5190. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  5191. << FDecl << Fn->getSourceRange());
  5192. // CUDA: Kernel function must have 'void' return type
  5193. if (!FuncT->getReturnType()->isVoidType())
  5194. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  5195. << Fn->getType() << Fn->getSourceRange());
  5196. } else {
  5197. // CUDA: Calls to global functions must be configured
  5198. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  5199. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  5200. << FDecl << Fn->getSourceRange());
  5201. }
  5202. }
  5203. // Check for a valid return type
  5204. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
  5205. FDecl))
  5206. return ExprError();
  5207. // We know the result type of the call, set it.
  5208. TheCall->setType(FuncT->getCallResultType(Context));
  5209. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  5210. if (Proto) {
  5211. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  5212. IsExecConfig))
  5213. return ExprError();
  5214. } else {
  5215. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  5216. if (FDecl) {
  5217. // Check if we have too few/too many template arguments, based
  5218. // on our knowledge of the function definition.
  5219. const FunctionDecl *Def = nullptr;
  5220. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  5221. Proto = Def->getType()->getAs<FunctionProtoType>();
  5222. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  5223. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  5224. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  5225. }
  5226. // If the function we're calling isn't a function prototype, but we have
  5227. // a function prototype from a prior declaratiom, use that prototype.
  5228. if (!FDecl->hasPrototype())
  5229. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  5230. }
  5231. // Promote the arguments (C99 6.5.2.2p6).
  5232. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  5233. Expr *Arg = Args[i];
  5234. if (Proto && i < Proto->getNumParams()) {
  5235. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  5236. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  5237. ExprResult ArgE =
  5238. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  5239. if (ArgE.isInvalid())
  5240. return true;
  5241. Arg = ArgE.getAs<Expr>();
  5242. } else {
  5243. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  5244. if (ArgE.isInvalid())
  5245. return true;
  5246. Arg = ArgE.getAs<Expr>();
  5247. }
  5248. if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
  5249. diag::err_call_incomplete_argument, Arg))
  5250. return ExprError();
  5251. TheCall->setArg(i, Arg);
  5252. }
  5253. }
  5254. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  5255. if (!Method->isStatic())
  5256. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  5257. << Fn->getSourceRange());
  5258. // Check for sentinels
  5259. if (NDecl)
  5260. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  5261. // Do special checking on direct calls to functions.
  5262. if (FDecl) {
  5263. if (CheckFunctionCall(FDecl, TheCall, Proto))
  5264. return ExprError();
  5265. checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
  5266. if (BuiltinID)
  5267. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  5268. } else if (NDecl) {
  5269. if (CheckPointerCall(NDecl, TheCall, Proto))
  5270. return ExprError();
  5271. } else {
  5272. if (CheckOtherCall(TheCall, Proto))
  5273. return ExprError();
  5274. }
  5275. return MaybeBindToTemporary(TheCall);
  5276. }
  5277. ExprResult
  5278. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  5279. SourceLocation RParenLoc, Expr *InitExpr) {
  5280. assert(Ty && "ActOnCompoundLiteral(): missing type");
  5281. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  5282. TypeSourceInfo *TInfo;
  5283. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  5284. if (!TInfo)
  5285. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  5286. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  5287. }
  5288. ExprResult
  5289. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  5290. SourceLocation RParenLoc, Expr *LiteralExpr) {
  5291. QualType literalType = TInfo->getType();
  5292. if (literalType->isArrayType()) {
  5293. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  5294. diag::err_illegal_decl_array_incomplete_type,
  5295. SourceRange(LParenLoc,
  5296. LiteralExpr->getSourceRange().getEnd())))
  5297. return ExprError();
  5298. if (literalType->isVariableArrayType())
  5299. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  5300. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  5301. } else if (!literalType->isDependentType() &&
  5302. RequireCompleteType(LParenLoc, literalType,
  5303. diag::err_typecheck_decl_incomplete_type,
  5304. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  5305. return ExprError();
  5306. InitializedEntity Entity
  5307. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  5308. InitializationKind Kind
  5309. = InitializationKind::CreateCStyleCast(LParenLoc,
  5310. SourceRange(LParenLoc, RParenLoc),
  5311. /*InitList=*/true);
  5312. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  5313. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  5314. &literalType);
  5315. if (Result.isInvalid())
  5316. return ExprError();
  5317. LiteralExpr = Result.get();
  5318. bool isFileScope = !CurContext->isFunctionOrMethod();
  5319. // In C, compound literals are l-values for some reason.
  5320. // For GCC compatibility, in C++, file-scope array compound literals with
  5321. // constant initializers are also l-values, and compound literals are
  5322. // otherwise prvalues.
  5323. //
  5324. // (GCC also treats C++ list-initialized file-scope array prvalues with
  5325. // constant initializers as l-values, but that's non-conforming, so we don't
  5326. // follow it there.)
  5327. //
  5328. // FIXME: It would be better to handle the lvalue cases as materializing and
  5329. // lifetime-extending a temporary object, but our materialized temporaries
  5330. // representation only supports lifetime extension from a variable, not "out
  5331. // of thin air".
  5332. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  5333. // is bound to the result of applying array-to-pointer decay to the compound
  5334. // literal.
  5335. // FIXME: GCC supports compound literals of reference type, which should
  5336. // obviously have a value kind derived from the kind of reference involved.
  5337. ExprValueKind VK =
  5338. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  5339. ? VK_RValue
  5340. : VK_LValue;
  5341. if (isFileScope)
  5342. if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
  5343. for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
  5344. Expr *Init = ILE->getInit(i);
  5345. ILE->setInit(i, ConstantExpr::Create(Context, Init));
  5346. }
  5347. Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  5348. VK, LiteralExpr, isFileScope);
  5349. if (isFileScope) {
  5350. if (!LiteralExpr->isTypeDependent() &&
  5351. !LiteralExpr->isValueDependent() &&
  5352. !literalType->isDependentType()) // C99 6.5.2.5p3
  5353. if (CheckForConstantInitializer(LiteralExpr, literalType))
  5354. return ExprError();
  5355. } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
  5356. literalType.getAddressSpace() != LangAS::Default) {
  5357. // Embedded-C extensions to C99 6.5.2.5:
  5358. // "If the compound literal occurs inside the body of a function, the
  5359. // type name shall not be qualified by an address-space qualifier."
  5360. Diag(LParenLoc, diag::err_compound_literal_with_address_space)
  5361. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
  5362. return ExprError();
  5363. }
  5364. return MaybeBindToTemporary(E);
  5365. }
  5366. ExprResult
  5367. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5368. SourceLocation RBraceLoc) {
  5369. // Only produce each kind of designated initialization diagnostic once.
  5370. SourceLocation FirstDesignator;
  5371. bool DiagnosedArrayDesignator = false;
  5372. bool DiagnosedNestedDesignator = false;
  5373. bool DiagnosedMixedDesignator = false;
  5374. // Check that any designated initializers are syntactically valid in the
  5375. // current language mode.
  5376. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5377. if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
  5378. if (FirstDesignator.isInvalid())
  5379. FirstDesignator = DIE->getBeginLoc();
  5380. if (!getLangOpts().CPlusPlus)
  5381. break;
  5382. if (!DiagnosedNestedDesignator && DIE->size() > 1) {
  5383. DiagnosedNestedDesignator = true;
  5384. Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
  5385. << DIE->getDesignatorsSourceRange();
  5386. }
  5387. for (auto &Desig : DIE->designators()) {
  5388. if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
  5389. DiagnosedArrayDesignator = true;
  5390. Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
  5391. << Desig.getSourceRange();
  5392. }
  5393. }
  5394. if (!DiagnosedMixedDesignator &&
  5395. !isa<DesignatedInitExpr>(InitArgList[0])) {
  5396. DiagnosedMixedDesignator = true;
  5397. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  5398. << DIE->getSourceRange();
  5399. Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
  5400. << InitArgList[0]->getSourceRange();
  5401. }
  5402. } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
  5403. isa<DesignatedInitExpr>(InitArgList[0])) {
  5404. DiagnosedMixedDesignator = true;
  5405. auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
  5406. Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
  5407. << DIE->getSourceRange();
  5408. Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
  5409. << InitArgList[I]->getSourceRange();
  5410. }
  5411. }
  5412. if (FirstDesignator.isValid()) {
  5413. // Only diagnose designated initiaization as a C++20 extension if we didn't
  5414. // already diagnose use of (non-C++20) C99 designator syntax.
  5415. if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
  5416. !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
  5417. Diag(FirstDesignator, getLangOpts().CPlusPlus2a
  5418. ? diag::warn_cxx17_compat_designated_init
  5419. : diag::ext_cxx_designated_init);
  5420. } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
  5421. Diag(FirstDesignator, diag::ext_designated_init);
  5422. }
  5423. }
  5424. return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
  5425. }
  5426. ExprResult
  5427. Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  5428. SourceLocation RBraceLoc) {
  5429. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5430. // CheckInitializer() - it requires knowledge of the object being initialized.
  5431. // Immediately handle non-overload placeholders. Overloads can be
  5432. // resolved contextually, but everything else here can't.
  5433. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  5434. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  5435. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5436. // Ignore failures; dropping the entire initializer list because
  5437. // of one failure would be terrible for indexing/etc.
  5438. if (result.isInvalid()) continue;
  5439. InitArgList[I] = result.get();
  5440. }
  5441. }
  5442. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5443. RBraceLoc);
  5444. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5445. return E;
  5446. }
  5447. /// Do an explicit extend of the given block pointer if we're in ARC.
  5448. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5449. assert(E.get()->getType()->isBlockPointerType());
  5450. assert(E.get()->isRValue());
  5451. // Only do this in an r-value context.
  5452. if (!getLangOpts().ObjCAutoRefCount) return;
  5453. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5454. CK_ARCExtendBlockObject, E.get(),
  5455. /*base path*/ nullptr, VK_RValue);
  5456. Cleanup.setExprNeedsCleanups(true);
  5457. }
  5458. /// Prepare a conversion of the given expression to an ObjC object
  5459. /// pointer type.
  5460. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5461. QualType type = E.get()->getType();
  5462. if (type->isObjCObjectPointerType()) {
  5463. return CK_BitCast;
  5464. } else if (type->isBlockPointerType()) {
  5465. maybeExtendBlockObject(E);
  5466. return CK_BlockPointerToObjCPointerCast;
  5467. } else {
  5468. assert(type->isPointerType());
  5469. return CK_CPointerToObjCPointerCast;
  5470. }
  5471. }
  5472. /// Prepares for a scalar cast, performing all the necessary stages
  5473. /// except the final cast and returning the kind required.
  5474. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5475. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5476. // Also, callers should have filtered out the invalid cases with
  5477. // pointers. Everything else should be possible.
  5478. QualType SrcTy = Src.get()->getType();
  5479. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5480. return CK_NoOp;
  5481. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5482. case Type::STK_MemberPointer:
  5483. llvm_unreachable("member pointer type in C");
  5484. case Type::STK_CPointer:
  5485. case Type::STK_BlockPointer:
  5486. case Type::STK_ObjCObjectPointer:
  5487. switch (DestTy->getScalarTypeKind()) {
  5488. case Type::STK_CPointer: {
  5489. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5490. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5491. if (SrcAS != DestAS)
  5492. return CK_AddressSpaceConversion;
  5493. if (Context.hasCvrSimilarType(SrcTy, DestTy))
  5494. return CK_NoOp;
  5495. return CK_BitCast;
  5496. }
  5497. case Type::STK_BlockPointer:
  5498. return (SrcKind == Type::STK_BlockPointer
  5499. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5500. case Type::STK_ObjCObjectPointer:
  5501. if (SrcKind == Type::STK_ObjCObjectPointer)
  5502. return CK_BitCast;
  5503. if (SrcKind == Type::STK_CPointer)
  5504. return CK_CPointerToObjCPointerCast;
  5505. maybeExtendBlockObject(Src);
  5506. return CK_BlockPointerToObjCPointerCast;
  5507. case Type::STK_Bool:
  5508. return CK_PointerToBoolean;
  5509. case Type::STK_Integral:
  5510. return CK_PointerToIntegral;
  5511. case Type::STK_Floating:
  5512. case Type::STK_FloatingComplex:
  5513. case Type::STK_IntegralComplex:
  5514. case Type::STK_MemberPointer:
  5515. case Type::STK_FixedPoint:
  5516. llvm_unreachable("illegal cast from pointer");
  5517. }
  5518. llvm_unreachable("Should have returned before this");
  5519. case Type::STK_FixedPoint:
  5520. switch (DestTy->getScalarTypeKind()) {
  5521. case Type::STK_FixedPoint:
  5522. return CK_FixedPointCast;
  5523. case Type::STK_Bool:
  5524. return CK_FixedPointToBoolean;
  5525. case Type::STK_Integral:
  5526. return CK_FixedPointToIntegral;
  5527. case Type::STK_Floating:
  5528. case Type::STK_IntegralComplex:
  5529. case Type::STK_FloatingComplex:
  5530. Diag(Src.get()->getExprLoc(),
  5531. diag::err_unimplemented_conversion_with_fixed_point_type)
  5532. << DestTy;
  5533. return CK_IntegralCast;
  5534. case Type::STK_CPointer:
  5535. case Type::STK_ObjCObjectPointer:
  5536. case Type::STK_BlockPointer:
  5537. case Type::STK_MemberPointer:
  5538. llvm_unreachable("illegal cast to pointer type");
  5539. }
  5540. llvm_unreachable("Should have returned before this");
  5541. case Type::STK_Bool: // casting from bool is like casting from an integer
  5542. case Type::STK_Integral:
  5543. switch (DestTy->getScalarTypeKind()) {
  5544. case Type::STK_CPointer:
  5545. case Type::STK_ObjCObjectPointer:
  5546. case Type::STK_BlockPointer:
  5547. if (Src.get()->isNullPointerConstant(Context,
  5548. Expr::NPC_ValueDependentIsNull))
  5549. return CK_NullToPointer;
  5550. return CK_IntegralToPointer;
  5551. case Type::STK_Bool:
  5552. return CK_IntegralToBoolean;
  5553. case Type::STK_Integral:
  5554. return CK_IntegralCast;
  5555. case Type::STK_Floating:
  5556. return CK_IntegralToFloating;
  5557. case Type::STK_IntegralComplex:
  5558. Src = ImpCastExprToType(Src.get(),
  5559. DestTy->castAs<ComplexType>()->getElementType(),
  5560. CK_IntegralCast);
  5561. return CK_IntegralRealToComplex;
  5562. case Type::STK_FloatingComplex:
  5563. Src = ImpCastExprToType(Src.get(),
  5564. DestTy->castAs<ComplexType>()->getElementType(),
  5565. CK_IntegralToFloating);
  5566. return CK_FloatingRealToComplex;
  5567. case Type::STK_MemberPointer:
  5568. llvm_unreachable("member pointer type in C");
  5569. case Type::STK_FixedPoint:
  5570. return CK_IntegralToFixedPoint;
  5571. }
  5572. llvm_unreachable("Should have returned before this");
  5573. case Type::STK_Floating:
  5574. switch (DestTy->getScalarTypeKind()) {
  5575. case Type::STK_Floating:
  5576. return CK_FloatingCast;
  5577. case Type::STK_Bool:
  5578. return CK_FloatingToBoolean;
  5579. case Type::STK_Integral:
  5580. return CK_FloatingToIntegral;
  5581. case Type::STK_FloatingComplex:
  5582. Src = ImpCastExprToType(Src.get(),
  5583. DestTy->castAs<ComplexType>()->getElementType(),
  5584. CK_FloatingCast);
  5585. return CK_FloatingRealToComplex;
  5586. case Type::STK_IntegralComplex:
  5587. Src = ImpCastExprToType(Src.get(),
  5588. DestTy->castAs<ComplexType>()->getElementType(),
  5589. CK_FloatingToIntegral);
  5590. return CK_IntegralRealToComplex;
  5591. case Type::STK_CPointer:
  5592. case Type::STK_ObjCObjectPointer:
  5593. case Type::STK_BlockPointer:
  5594. llvm_unreachable("valid float->pointer cast?");
  5595. case Type::STK_MemberPointer:
  5596. llvm_unreachable("member pointer type in C");
  5597. case Type::STK_FixedPoint:
  5598. Diag(Src.get()->getExprLoc(),
  5599. diag::err_unimplemented_conversion_with_fixed_point_type)
  5600. << SrcTy;
  5601. return CK_IntegralCast;
  5602. }
  5603. llvm_unreachable("Should have returned before this");
  5604. case Type::STK_FloatingComplex:
  5605. switch (DestTy->getScalarTypeKind()) {
  5606. case Type::STK_FloatingComplex:
  5607. return CK_FloatingComplexCast;
  5608. case Type::STK_IntegralComplex:
  5609. return CK_FloatingComplexToIntegralComplex;
  5610. case Type::STK_Floating: {
  5611. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5612. if (Context.hasSameType(ET, DestTy))
  5613. return CK_FloatingComplexToReal;
  5614. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5615. return CK_FloatingCast;
  5616. }
  5617. case Type::STK_Bool:
  5618. return CK_FloatingComplexToBoolean;
  5619. case Type::STK_Integral:
  5620. Src = ImpCastExprToType(Src.get(),
  5621. SrcTy->castAs<ComplexType>()->getElementType(),
  5622. CK_FloatingComplexToReal);
  5623. return CK_FloatingToIntegral;
  5624. case Type::STK_CPointer:
  5625. case Type::STK_ObjCObjectPointer:
  5626. case Type::STK_BlockPointer:
  5627. llvm_unreachable("valid complex float->pointer cast?");
  5628. case Type::STK_MemberPointer:
  5629. llvm_unreachable("member pointer type in C");
  5630. case Type::STK_FixedPoint:
  5631. Diag(Src.get()->getExprLoc(),
  5632. diag::err_unimplemented_conversion_with_fixed_point_type)
  5633. << SrcTy;
  5634. return CK_IntegralCast;
  5635. }
  5636. llvm_unreachable("Should have returned before this");
  5637. case Type::STK_IntegralComplex:
  5638. switch (DestTy->getScalarTypeKind()) {
  5639. case Type::STK_FloatingComplex:
  5640. return CK_IntegralComplexToFloatingComplex;
  5641. case Type::STK_IntegralComplex:
  5642. return CK_IntegralComplexCast;
  5643. case Type::STK_Integral: {
  5644. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5645. if (Context.hasSameType(ET, DestTy))
  5646. return CK_IntegralComplexToReal;
  5647. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5648. return CK_IntegralCast;
  5649. }
  5650. case Type::STK_Bool:
  5651. return CK_IntegralComplexToBoolean;
  5652. case Type::STK_Floating:
  5653. Src = ImpCastExprToType(Src.get(),
  5654. SrcTy->castAs<ComplexType>()->getElementType(),
  5655. CK_IntegralComplexToReal);
  5656. return CK_IntegralToFloating;
  5657. case Type::STK_CPointer:
  5658. case Type::STK_ObjCObjectPointer:
  5659. case Type::STK_BlockPointer:
  5660. llvm_unreachable("valid complex int->pointer cast?");
  5661. case Type::STK_MemberPointer:
  5662. llvm_unreachable("member pointer type in C");
  5663. case Type::STK_FixedPoint:
  5664. Diag(Src.get()->getExprLoc(),
  5665. diag::err_unimplemented_conversion_with_fixed_point_type)
  5666. << SrcTy;
  5667. return CK_IntegralCast;
  5668. }
  5669. llvm_unreachable("Should have returned before this");
  5670. }
  5671. llvm_unreachable("Unhandled scalar cast");
  5672. }
  5673. static bool breakDownVectorType(QualType type, uint64_t &len,
  5674. QualType &eltType) {
  5675. // Vectors are simple.
  5676. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5677. len = vecType->getNumElements();
  5678. eltType = vecType->getElementType();
  5679. assert(eltType->isScalarType());
  5680. return true;
  5681. }
  5682. // We allow lax conversion to and from non-vector types, but only if
  5683. // they're real types (i.e. non-complex, non-pointer scalar types).
  5684. if (!type->isRealType()) return false;
  5685. len = 1;
  5686. eltType = type;
  5687. return true;
  5688. }
  5689. /// Are the two types lax-compatible vector types? That is, given
  5690. /// that one of them is a vector, do they have equal storage sizes,
  5691. /// where the storage size is the number of elements times the element
  5692. /// size?
  5693. ///
  5694. /// This will also return false if either of the types is neither a
  5695. /// vector nor a real type.
  5696. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5697. assert(destTy->isVectorType() || srcTy->isVectorType());
  5698. // Disallow lax conversions between scalars and ExtVectors (these
  5699. // conversions are allowed for other vector types because common headers
  5700. // depend on them). Most scalar OP ExtVector cases are handled by the
  5701. // splat path anyway, which does what we want (convert, not bitcast).
  5702. // What this rules out for ExtVectors is crazy things like char4*float.
  5703. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5704. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5705. uint64_t srcLen, destLen;
  5706. QualType srcEltTy, destEltTy;
  5707. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5708. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5709. // ASTContext::getTypeSize will return the size rounded up to a
  5710. // power of 2, so instead of using that, we need to use the raw
  5711. // element size multiplied by the element count.
  5712. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5713. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5714. return (srcLen * srcEltSize == destLen * destEltSize);
  5715. }
  5716. /// Is this a legal conversion between two types, one of which is
  5717. /// known to be a vector type?
  5718. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5719. assert(destTy->isVectorType() || srcTy->isVectorType());
  5720. if (!Context.getLangOpts().LaxVectorConversions)
  5721. return false;
  5722. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5723. }
  5724. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5725. CastKind &Kind) {
  5726. assert(VectorTy->isVectorType() && "Not a vector type!");
  5727. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5728. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5729. return Diag(R.getBegin(),
  5730. Ty->isVectorType() ?
  5731. diag::err_invalid_conversion_between_vectors :
  5732. diag::err_invalid_conversion_between_vector_and_integer)
  5733. << VectorTy << Ty << R;
  5734. } else
  5735. return Diag(R.getBegin(),
  5736. diag::err_invalid_conversion_between_vector_and_scalar)
  5737. << VectorTy << Ty << R;
  5738. Kind = CK_BitCast;
  5739. return false;
  5740. }
  5741. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5742. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5743. if (DestElemTy == SplattedExpr->getType())
  5744. return SplattedExpr;
  5745. assert(DestElemTy->isFloatingType() ||
  5746. DestElemTy->isIntegralOrEnumerationType());
  5747. CastKind CK;
  5748. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5749. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5750. // only when splatting vectors.
  5751. if (DestElemTy->isFloatingType()) {
  5752. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5753. // in two steps: boolean to signed integral, then to floating.
  5754. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5755. CK_BooleanToSignedIntegral);
  5756. SplattedExpr = CastExprRes.get();
  5757. CK = CK_IntegralToFloating;
  5758. } else {
  5759. CK = CK_BooleanToSignedIntegral;
  5760. }
  5761. } else {
  5762. ExprResult CastExprRes = SplattedExpr;
  5763. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5764. if (CastExprRes.isInvalid())
  5765. return ExprError();
  5766. SplattedExpr = CastExprRes.get();
  5767. }
  5768. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5769. }
  5770. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5771. Expr *CastExpr, CastKind &Kind) {
  5772. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5773. QualType SrcTy = CastExpr->getType();
  5774. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5775. // an ExtVectorType.
  5776. // In OpenCL, casts between vectors of different types are not allowed.
  5777. // (See OpenCL 6.2).
  5778. if (SrcTy->isVectorType()) {
  5779. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5780. (getLangOpts().OpenCL &&
  5781. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5782. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5783. << DestTy << SrcTy << R;
  5784. return ExprError();
  5785. }
  5786. Kind = CK_BitCast;
  5787. return CastExpr;
  5788. }
  5789. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5790. // conversion will take place first from scalar to elt type, and then
  5791. // splat from elt type to vector.
  5792. if (SrcTy->isPointerType())
  5793. return Diag(R.getBegin(),
  5794. diag::err_invalid_conversion_between_vector_and_scalar)
  5795. << DestTy << SrcTy << R;
  5796. Kind = CK_VectorSplat;
  5797. return prepareVectorSplat(DestTy, CastExpr);
  5798. }
  5799. ExprResult
  5800. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5801. Declarator &D, ParsedType &Ty,
  5802. SourceLocation RParenLoc, Expr *CastExpr) {
  5803. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5804. "ActOnCastExpr(): missing type or expr");
  5805. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5806. if (D.isInvalidType())
  5807. return ExprError();
  5808. if (getLangOpts().CPlusPlus) {
  5809. // Check that there are no default arguments (C++ only).
  5810. CheckExtraCXXDefaultArguments(D);
  5811. } else {
  5812. // Make sure any TypoExprs have been dealt with.
  5813. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5814. if (!Res.isUsable())
  5815. return ExprError();
  5816. CastExpr = Res.get();
  5817. }
  5818. checkUnusedDeclAttributes(D);
  5819. QualType castType = castTInfo->getType();
  5820. Ty = CreateParsedType(castType, castTInfo);
  5821. bool isVectorLiteral = false;
  5822. // Check for an altivec or OpenCL literal,
  5823. // i.e. all the elements are integer constants.
  5824. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5825. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5826. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5827. && castType->isVectorType() && (PE || PLE)) {
  5828. if (PLE && PLE->getNumExprs() == 0) {
  5829. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5830. return ExprError();
  5831. }
  5832. if (PE || PLE->getNumExprs() == 1) {
  5833. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5834. if (!E->getType()->isVectorType())
  5835. isVectorLiteral = true;
  5836. }
  5837. else
  5838. isVectorLiteral = true;
  5839. }
  5840. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5841. // then handle it as such.
  5842. if (isVectorLiteral)
  5843. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5844. // If the Expr being casted is a ParenListExpr, handle it specially.
  5845. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5846. // sequence of BinOp comma operators.
  5847. if (isa<ParenListExpr>(CastExpr)) {
  5848. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5849. if (Result.isInvalid()) return ExprError();
  5850. CastExpr = Result.get();
  5851. }
  5852. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5853. !getSourceManager().isInSystemMacro(LParenLoc))
  5854. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5855. CheckTollFreeBridgeCast(castType, CastExpr);
  5856. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5857. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5858. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5859. }
  5860. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5861. SourceLocation RParenLoc, Expr *E,
  5862. TypeSourceInfo *TInfo) {
  5863. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5864. "Expected paren or paren list expression");
  5865. Expr **exprs;
  5866. unsigned numExprs;
  5867. Expr *subExpr;
  5868. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5869. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5870. LiteralLParenLoc = PE->getLParenLoc();
  5871. LiteralRParenLoc = PE->getRParenLoc();
  5872. exprs = PE->getExprs();
  5873. numExprs = PE->getNumExprs();
  5874. } else { // isa<ParenExpr> by assertion at function entrance
  5875. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5876. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5877. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5878. exprs = &subExpr;
  5879. numExprs = 1;
  5880. }
  5881. QualType Ty = TInfo->getType();
  5882. assert(Ty->isVectorType() && "Expected vector type");
  5883. SmallVector<Expr *, 8> initExprs;
  5884. const VectorType *VTy = Ty->getAs<VectorType>();
  5885. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5886. // '(...)' form of vector initialization in AltiVec: the number of
  5887. // initializers must be one or must match the size of the vector.
  5888. // If a single value is specified in the initializer then it will be
  5889. // replicated to all the components of the vector
  5890. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5891. // The number of initializers must be one or must match the size of the
  5892. // vector. If a single value is specified in the initializer then it will
  5893. // be replicated to all the components of the vector
  5894. if (numExprs == 1) {
  5895. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5896. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5897. if (Literal.isInvalid())
  5898. return ExprError();
  5899. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5900. PrepareScalarCast(Literal, ElemTy));
  5901. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5902. }
  5903. else if (numExprs < numElems) {
  5904. Diag(E->getExprLoc(),
  5905. diag::err_incorrect_number_of_vector_initializers);
  5906. return ExprError();
  5907. }
  5908. else
  5909. initExprs.append(exprs, exprs + numExprs);
  5910. }
  5911. else {
  5912. // For OpenCL, when the number of initializers is a single value,
  5913. // it will be replicated to all components of the vector.
  5914. if (getLangOpts().OpenCL &&
  5915. VTy->getVectorKind() == VectorType::GenericVector &&
  5916. numExprs == 1) {
  5917. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5918. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5919. if (Literal.isInvalid())
  5920. return ExprError();
  5921. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5922. PrepareScalarCast(Literal, ElemTy));
  5923. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5924. }
  5925. initExprs.append(exprs, exprs + numExprs);
  5926. }
  5927. // FIXME: This means that pretty-printing the final AST will produce curly
  5928. // braces instead of the original commas.
  5929. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5930. initExprs, LiteralRParenLoc);
  5931. initE->setType(Ty);
  5932. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5933. }
  5934. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5935. /// the ParenListExpr into a sequence of comma binary operators.
  5936. ExprResult
  5937. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5938. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5939. if (!E)
  5940. return OrigExpr;
  5941. ExprResult Result(E->getExpr(0));
  5942. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5943. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5944. E->getExpr(i));
  5945. if (Result.isInvalid()) return ExprError();
  5946. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5947. }
  5948. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5949. SourceLocation R,
  5950. MultiExprArg Val) {
  5951. return ParenListExpr::Create(Context, L, Val, R);
  5952. }
  5953. /// Emit a specialized diagnostic when one expression is a null pointer
  5954. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5955. /// emitted.
  5956. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5957. SourceLocation QuestionLoc) {
  5958. Expr *NullExpr = LHSExpr;
  5959. Expr *NonPointerExpr = RHSExpr;
  5960. Expr::NullPointerConstantKind NullKind =
  5961. NullExpr->isNullPointerConstant(Context,
  5962. Expr::NPC_ValueDependentIsNotNull);
  5963. if (NullKind == Expr::NPCK_NotNull) {
  5964. NullExpr = RHSExpr;
  5965. NonPointerExpr = LHSExpr;
  5966. NullKind =
  5967. NullExpr->isNullPointerConstant(Context,
  5968. Expr::NPC_ValueDependentIsNotNull);
  5969. }
  5970. if (NullKind == Expr::NPCK_NotNull)
  5971. return false;
  5972. if (NullKind == Expr::NPCK_ZeroExpression)
  5973. return false;
  5974. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5975. // In this case, check to make sure that we got here from a "NULL"
  5976. // string in the source code.
  5977. NullExpr = NullExpr->IgnoreParenImpCasts();
  5978. SourceLocation loc = NullExpr->getExprLoc();
  5979. if (!findMacroSpelling(loc, "NULL"))
  5980. return false;
  5981. }
  5982. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5983. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5984. << NonPointerExpr->getType() << DiagType
  5985. << NonPointerExpr->getSourceRange();
  5986. return true;
  5987. }
  5988. /// Return false if the condition expression is valid, true otherwise.
  5989. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5990. QualType CondTy = Cond->getType();
  5991. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5992. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5993. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5994. << CondTy << Cond->getSourceRange();
  5995. return true;
  5996. }
  5997. // C99 6.5.15p2
  5998. if (CondTy->isScalarType()) return false;
  5999. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  6000. << CondTy << Cond->getSourceRange();
  6001. return true;
  6002. }
  6003. /// Handle when one or both operands are void type.
  6004. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  6005. ExprResult &RHS) {
  6006. Expr *LHSExpr = LHS.get();
  6007. Expr *RHSExpr = RHS.get();
  6008. if (!LHSExpr->getType()->isVoidType())
  6009. S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  6010. << RHSExpr->getSourceRange();
  6011. if (!RHSExpr->getType()->isVoidType())
  6012. S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
  6013. << LHSExpr->getSourceRange();
  6014. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  6015. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  6016. return S.Context.VoidTy;
  6017. }
  6018. /// Return false if the NullExpr can be promoted to PointerTy,
  6019. /// true otherwise.
  6020. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  6021. QualType PointerTy) {
  6022. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  6023. !NullExpr.get()->isNullPointerConstant(S.Context,
  6024. Expr::NPC_ValueDependentIsNull))
  6025. return true;
  6026. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  6027. return false;
  6028. }
  6029. /// Checks compatibility between two pointers and return the resulting
  6030. /// type.
  6031. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  6032. ExprResult &RHS,
  6033. SourceLocation Loc) {
  6034. QualType LHSTy = LHS.get()->getType();
  6035. QualType RHSTy = RHS.get()->getType();
  6036. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  6037. // Two identical pointers types are always compatible.
  6038. return LHSTy;
  6039. }
  6040. QualType lhptee, rhptee;
  6041. // Get the pointee types.
  6042. bool IsBlockPointer = false;
  6043. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  6044. lhptee = LHSBTy->getPointeeType();
  6045. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  6046. IsBlockPointer = true;
  6047. } else {
  6048. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  6049. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  6050. }
  6051. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  6052. // differently qualified versions of compatible types, the result type is
  6053. // a pointer to an appropriately qualified version of the composite
  6054. // type.
  6055. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  6056. // clause doesn't make sense for our extensions. E.g. address space 2 should
  6057. // be incompatible with address space 3: they may live on different devices or
  6058. // anything.
  6059. Qualifiers lhQual = lhptee.getQualifiers();
  6060. Qualifiers rhQual = rhptee.getQualifiers();
  6061. LangAS ResultAddrSpace = LangAS::Default;
  6062. LangAS LAddrSpace = lhQual.getAddressSpace();
  6063. LangAS RAddrSpace = rhQual.getAddressSpace();
  6064. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  6065. // spaces is disallowed.
  6066. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  6067. ResultAddrSpace = LAddrSpace;
  6068. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  6069. ResultAddrSpace = RAddrSpace;
  6070. else {
  6071. S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  6072. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  6073. << RHS.get()->getSourceRange();
  6074. return QualType();
  6075. }
  6076. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  6077. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  6078. lhQual.removeCVRQualifiers();
  6079. rhQual.removeCVRQualifiers();
  6080. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  6081. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  6082. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  6083. // qual types are compatible iff
  6084. // * corresponded types are compatible
  6085. // * CVR qualifiers are equal
  6086. // * address spaces are equal
  6087. // Thus for conditional operator we merge CVR and address space unqualified
  6088. // pointees and if there is a composite type we return a pointer to it with
  6089. // merged qualifiers.
  6090. LHSCastKind =
  6091. LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6092. RHSCastKind =
  6093. RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
  6094. lhQual.removeAddressSpace();
  6095. rhQual.removeAddressSpace();
  6096. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  6097. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  6098. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  6099. if (CompositeTy.isNull()) {
  6100. // In this situation, we assume void* type. No especially good
  6101. // reason, but this is what gcc does, and we do have to pick
  6102. // to get a consistent AST.
  6103. QualType incompatTy;
  6104. incompatTy = S.Context.getPointerType(
  6105. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  6106. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  6107. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  6108. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  6109. // for casts between types with incompatible address space qualifiers.
  6110. // For the following code the compiler produces casts between global and
  6111. // local address spaces of the corresponded innermost pointees:
  6112. // local int *global *a;
  6113. // global int *global *b;
  6114. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  6115. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  6116. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6117. << RHS.get()->getSourceRange();
  6118. return incompatTy;
  6119. }
  6120. // The pointer types are compatible.
  6121. // In case of OpenCL ResultTy should have the address space qualifier
  6122. // which is a superset of address spaces of both the 2nd and the 3rd
  6123. // operands of the conditional operator.
  6124. QualType ResultTy = [&, ResultAddrSpace]() {
  6125. if (S.getLangOpts().OpenCL) {
  6126. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  6127. CompositeQuals.setAddressSpace(ResultAddrSpace);
  6128. return S.Context
  6129. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  6130. .withCVRQualifiers(MergedCVRQual);
  6131. }
  6132. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  6133. }();
  6134. if (IsBlockPointer)
  6135. ResultTy = S.Context.getBlockPointerType(ResultTy);
  6136. else
  6137. ResultTy = S.Context.getPointerType(ResultTy);
  6138. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  6139. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  6140. return ResultTy;
  6141. }
  6142. /// Return the resulting type when the operands are both block pointers.
  6143. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  6144. ExprResult &LHS,
  6145. ExprResult &RHS,
  6146. SourceLocation Loc) {
  6147. QualType LHSTy = LHS.get()->getType();
  6148. QualType RHSTy = RHS.get()->getType();
  6149. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  6150. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  6151. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  6152. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6153. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6154. return destType;
  6155. }
  6156. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  6157. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6158. << RHS.get()->getSourceRange();
  6159. return QualType();
  6160. }
  6161. // We have 2 block pointer types.
  6162. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6163. }
  6164. /// Return the resulting type when the operands are both pointers.
  6165. static QualType
  6166. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  6167. ExprResult &RHS,
  6168. SourceLocation Loc) {
  6169. // get the pointer types
  6170. QualType LHSTy = LHS.get()->getType();
  6171. QualType RHSTy = RHS.get()->getType();
  6172. // get the "pointed to" types
  6173. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6174. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6175. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  6176. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  6177. // Figure out necessary qualifiers (C99 6.5.15p6)
  6178. QualType destPointee
  6179. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6180. QualType destType = S.Context.getPointerType(destPointee);
  6181. // Add qualifiers if necessary.
  6182. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6183. // Promote to void*.
  6184. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6185. return destType;
  6186. }
  6187. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  6188. QualType destPointee
  6189. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6190. QualType destType = S.Context.getPointerType(destPointee);
  6191. // Add qualifiers if necessary.
  6192. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6193. // Promote to void*.
  6194. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6195. return destType;
  6196. }
  6197. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  6198. }
  6199. /// Return false if the first expression is not an integer and the second
  6200. /// expression is not a pointer, true otherwise.
  6201. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  6202. Expr* PointerExpr, SourceLocation Loc,
  6203. bool IsIntFirstExpr) {
  6204. if (!PointerExpr->getType()->isPointerType() ||
  6205. !Int.get()->getType()->isIntegerType())
  6206. return false;
  6207. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  6208. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  6209. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  6210. << Expr1->getType() << Expr2->getType()
  6211. << Expr1->getSourceRange() << Expr2->getSourceRange();
  6212. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  6213. CK_IntegralToPointer);
  6214. return true;
  6215. }
  6216. /// Simple conversion between integer and floating point types.
  6217. ///
  6218. /// Used when handling the OpenCL conditional operator where the
  6219. /// condition is a vector while the other operands are scalar.
  6220. ///
  6221. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  6222. /// types are either integer or floating type. Between the two
  6223. /// operands, the type with the higher rank is defined as the "result
  6224. /// type". The other operand needs to be promoted to the same type. No
  6225. /// other type promotion is allowed. We cannot use
  6226. /// UsualArithmeticConversions() for this purpose, since it always
  6227. /// promotes promotable types.
  6228. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  6229. ExprResult &RHS,
  6230. SourceLocation QuestionLoc) {
  6231. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  6232. if (LHS.isInvalid())
  6233. return QualType();
  6234. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  6235. if (RHS.isInvalid())
  6236. return QualType();
  6237. // For conversion purposes, we ignore any qualifiers.
  6238. // For example, "const float" and "float" are equivalent.
  6239. QualType LHSType =
  6240. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  6241. QualType RHSType =
  6242. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  6243. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  6244. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6245. << LHSType << LHS.get()->getSourceRange();
  6246. return QualType();
  6247. }
  6248. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  6249. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  6250. << RHSType << RHS.get()->getSourceRange();
  6251. return QualType();
  6252. }
  6253. // If both types are identical, no conversion is needed.
  6254. if (LHSType == RHSType)
  6255. return LHSType;
  6256. // Now handle "real" floating types (i.e. float, double, long double).
  6257. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  6258. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  6259. /*IsCompAssign = */ false);
  6260. // Finally, we have two differing integer types.
  6261. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  6262. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  6263. }
  6264. /// Convert scalar operands to a vector that matches the
  6265. /// condition in length.
  6266. ///
  6267. /// Used when handling the OpenCL conditional operator where the
  6268. /// condition is a vector while the other operands are scalar.
  6269. ///
  6270. /// We first compute the "result type" for the scalar operands
  6271. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  6272. /// into a vector of that type where the length matches the condition
  6273. /// vector type. s6.11.6 requires that the element types of the result
  6274. /// and the condition must have the same number of bits.
  6275. static QualType
  6276. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  6277. QualType CondTy, SourceLocation QuestionLoc) {
  6278. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  6279. if (ResTy.isNull()) return QualType();
  6280. const VectorType *CV = CondTy->getAs<VectorType>();
  6281. assert(CV);
  6282. // Determine the vector result type
  6283. unsigned NumElements = CV->getNumElements();
  6284. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  6285. // Ensure that all types have the same number of bits
  6286. if (S.Context.getTypeSize(CV->getElementType())
  6287. != S.Context.getTypeSize(ResTy)) {
  6288. // Since VectorTy is created internally, it does not pretty print
  6289. // with an OpenCL name. Instead, we just print a description.
  6290. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  6291. SmallString<64> Str;
  6292. llvm::raw_svector_ostream OS(Str);
  6293. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  6294. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6295. << CondTy << OS.str();
  6296. return QualType();
  6297. }
  6298. // Convert operands to the vector result type
  6299. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  6300. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  6301. return VectorTy;
  6302. }
  6303. /// Return false if this is a valid OpenCL condition vector
  6304. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  6305. SourceLocation QuestionLoc) {
  6306. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  6307. // integral type.
  6308. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  6309. assert(CondTy);
  6310. QualType EleTy = CondTy->getElementType();
  6311. if (EleTy->isIntegerType()) return false;
  6312. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  6313. << Cond->getType() << Cond->getSourceRange();
  6314. return true;
  6315. }
  6316. /// Return false if the vector condition type and the vector
  6317. /// result type are compatible.
  6318. ///
  6319. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  6320. /// number of elements, and their element types have the same number
  6321. /// of bits.
  6322. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  6323. SourceLocation QuestionLoc) {
  6324. const VectorType *CV = CondTy->getAs<VectorType>();
  6325. const VectorType *RV = VecResTy->getAs<VectorType>();
  6326. assert(CV && RV);
  6327. if (CV->getNumElements() != RV->getNumElements()) {
  6328. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  6329. << CondTy << VecResTy;
  6330. return true;
  6331. }
  6332. QualType CVE = CV->getElementType();
  6333. QualType RVE = RV->getElementType();
  6334. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  6335. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  6336. << CondTy << VecResTy;
  6337. return true;
  6338. }
  6339. return false;
  6340. }
  6341. /// Return the resulting type for the conditional operator in
  6342. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  6343. /// s6.3.i) when the condition is a vector type.
  6344. static QualType
  6345. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  6346. ExprResult &LHS, ExprResult &RHS,
  6347. SourceLocation QuestionLoc) {
  6348. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  6349. if (Cond.isInvalid())
  6350. return QualType();
  6351. QualType CondTy = Cond.get()->getType();
  6352. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  6353. return QualType();
  6354. // If either operand is a vector then find the vector type of the
  6355. // result as specified in OpenCL v1.1 s6.3.i.
  6356. if (LHS.get()->getType()->isVectorType() ||
  6357. RHS.get()->getType()->isVectorType()) {
  6358. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  6359. /*isCompAssign*/false,
  6360. /*AllowBothBool*/true,
  6361. /*AllowBoolConversions*/false);
  6362. if (VecResTy.isNull()) return QualType();
  6363. // The result type must match the condition type as specified in
  6364. // OpenCL v1.1 s6.11.6.
  6365. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  6366. return QualType();
  6367. return VecResTy;
  6368. }
  6369. // Both operands are scalar.
  6370. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  6371. }
  6372. /// Return true if the Expr is block type
  6373. static bool checkBlockType(Sema &S, const Expr *E) {
  6374. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  6375. QualType Ty = CE->getCallee()->getType();
  6376. if (Ty->isBlockPointerType()) {
  6377. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  6378. return true;
  6379. }
  6380. }
  6381. return false;
  6382. }
  6383. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  6384. /// In that case, LHS = cond.
  6385. /// C99 6.5.15
  6386. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  6387. ExprResult &RHS, ExprValueKind &VK,
  6388. ExprObjectKind &OK,
  6389. SourceLocation QuestionLoc) {
  6390. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  6391. if (!LHSResult.isUsable()) return QualType();
  6392. LHS = LHSResult;
  6393. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  6394. if (!RHSResult.isUsable()) return QualType();
  6395. RHS = RHSResult;
  6396. // C++ is sufficiently different to merit its own checker.
  6397. if (getLangOpts().CPlusPlus)
  6398. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  6399. VK = VK_RValue;
  6400. OK = OK_Ordinary;
  6401. // The OpenCL operator with a vector condition is sufficiently
  6402. // different to merit its own checker.
  6403. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  6404. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  6405. // First, check the condition.
  6406. Cond = UsualUnaryConversions(Cond.get());
  6407. if (Cond.isInvalid())
  6408. return QualType();
  6409. if (checkCondition(*this, Cond.get(), QuestionLoc))
  6410. return QualType();
  6411. // Now check the two expressions.
  6412. if (LHS.get()->getType()->isVectorType() ||
  6413. RHS.get()->getType()->isVectorType())
  6414. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  6415. /*AllowBothBool*/true,
  6416. /*AllowBoolConversions*/false);
  6417. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  6418. if (LHS.isInvalid() || RHS.isInvalid())
  6419. return QualType();
  6420. QualType LHSTy = LHS.get()->getType();
  6421. QualType RHSTy = RHS.get()->getType();
  6422. // Diagnose attempts to convert between __float128 and long double where
  6423. // such conversions currently can't be handled.
  6424. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  6425. Diag(QuestionLoc,
  6426. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  6427. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6428. return QualType();
  6429. }
  6430. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  6431. // selection operator (?:).
  6432. if (getLangOpts().OpenCL &&
  6433. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  6434. return QualType();
  6435. }
  6436. // If both operands have arithmetic type, do the usual arithmetic conversions
  6437. // to find a common type: C99 6.5.15p3,5.
  6438. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  6439. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  6440. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  6441. return ResTy;
  6442. }
  6443. // If both operands are the same structure or union type, the result is that
  6444. // type.
  6445. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  6446. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  6447. if (LHSRT->getDecl() == RHSRT->getDecl())
  6448. // "If both the operands have structure or union type, the result has
  6449. // that type." This implies that CV qualifiers are dropped.
  6450. return LHSTy.getUnqualifiedType();
  6451. // FIXME: Type of conditional expression must be complete in C mode.
  6452. }
  6453. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  6454. // The following || allows only one side to be void (a GCC-ism).
  6455. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  6456. return checkConditionalVoidType(*this, LHS, RHS);
  6457. }
  6458. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  6459. // the type of the other operand."
  6460. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  6461. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  6462. // All objective-c pointer type analysis is done here.
  6463. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  6464. QuestionLoc);
  6465. if (LHS.isInvalid() || RHS.isInvalid())
  6466. return QualType();
  6467. if (!compositeType.isNull())
  6468. return compositeType;
  6469. // Handle block pointer types.
  6470. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6471. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6472. QuestionLoc);
  6473. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6474. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6475. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6476. QuestionLoc);
  6477. // GCC compatibility: soften pointer/integer mismatch. Note that
  6478. // null pointers have been filtered out by this point.
  6479. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6480. /*IsIntFirstExpr=*/true))
  6481. return RHSTy;
  6482. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6483. /*IsIntFirstExpr=*/false))
  6484. return LHSTy;
  6485. // Emit a better diagnostic if one of the expressions is a null pointer
  6486. // constant and the other is not a pointer type. In this case, the user most
  6487. // likely forgot to take the address of the other expression.
  6488. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6489. return QualType();
  6490. // Otherwise, the operands are not compatible.
  6491. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6492. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6493. << RHS.get()->getSourceRange();
  6494. return QualType();
  6495. }
  6496. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6497. /// two objective-c pointer types of the two input expressions.
  6498. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6499. SourceLocation QuestionLoc) {
  6500. QualType LHSTy = LHS.get()->getType();
  6501. QualType RHSTy = RHS.get()->getType();
  6502. // Handle things like Class and struct objc_class*. Here we case the result
  6503. // to the pseudo-builtin, because that will be implicitly cast back to the
  6504. // redefinition type if an attempt is made to access its fields.
  6505. if (LHSTy->isObjCClassType() &&
  6506. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6507. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6508. return LHSTy;
  6509. }
  6510. if (RHSTy->isObjCClassType() &&
  6511. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6512. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6513. return RHSTy;
  6514. }
  6515. // And the same for struct objc_object* / id
  6516. if (LHSTy->isObjCIdType() &&
  6517. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6518. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6519. return LHSTy;
  6520. }
  6521. if (RHSTy->isObjCIdType() &&
  6522. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6523. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6524. return RHSTy;
  6525. }
  6526. // And the same for struct objc_selector* / SEL
  6527. if (Context.isObjCSelType(LHSTy) &&
  6528. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6529. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6530. return LHSTy;
  6531. }
  6532. if (Context.isObjCSelType(RHSTy) &&
  6533. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6534. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6535. return RHSTy;
  6536. }
  6537. // Check constraints for Objective-C object pointers types.
  6538. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6539. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6540. // Two identical object pointer types are always compatible.
  6541. return LHSTy;
  6542. }
  6543. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6544. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6545. QualType compositeType = LHSTy;
  6546. // If both operands are interfaces and either operand can be
  6547. // assigned to the other, use that type as the composite
  6548. // type. This allows
  6549. // xxx ? (A*) a : (B*) b
  6550. // where B is a subclass of A.
  6551. //
  6552. // Additionally, as for assignment, if either type is 'id'
  6553. // allow silent coercion. Finally, if the types are
  6554. // incompatible then make sure to use 'id' as the composite
  6555. // type so the result is acceptable for sending messages to.
  6556. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6557. // It could return the composite type.
  6558. if (!(compositeType =
  6559. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6560. // Nothing more to do.
  6561. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6562. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6563. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6564. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6565. } else if ((LHSTy->isObjCQualifiedIdType() ||
  6566. RHSTy->isObjCQualifiedIdType()) &&
  6567. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  6568. // Need to handle "id<xx>" explicitly.
  6569. // GCC allows qualified id and any Objective-C type to devolve to
  6570. // id. Currently localizing to here until clear this should be
  6571. // part of ObjCQualifiedIdTypesAreCompatible.
  6572. compositeType = Context.getObjCIdType();
  6573. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6574. compositeType = Context.getObjCIdType();
  6575. } else {
  6576. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6577. << LHSTy << RHSTy
  6578. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6579. QualType incompatTy = Context.getObjCIdType();
  6580. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6581. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6582. return incompatTy;
  6583. }
  6584. // The object pointer types are compatible.
  6585. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6586. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6587. return compositeType;
  6588. }
  6589. // Check Objective-C object pointer types and 'void *'
  6590. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6591. if (getLangOpts().ObjCAutoRefCount) {
  6592. // ARC forbids the implicit conversion of object pointers to 'void *',
  6593. // so these types are not compatible.
  6594. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6595. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6596. LHS = RHS = true;
  6597. return QualType();
  6598. }
  6599. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6600. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6601. QualType destPointee
  6602. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6603. QualType destType = Context.getPointerType(destPointee);
  6604. // Add qualifiers if necessary.
  6605. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6606. // Promote to void*.
  6607. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6608. return destType;
  6609. }
  6610. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6611. if (getLangOpts().ObjCAutoRefCount) {
  6612. // ARC forbids the implicit conversion of object pointers to 'void *',
  6613. // so these types are not compatible.
  6614. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6615. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6616. LHS = RHS = true;
  6617. return QualType();
  6618. }
  6619. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6620. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6621. QualType destPointee
  6622. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6623. QualType destType = Context.getPointerType(destPointee);
  6624. // Add qualifiers if necessary.
  6625. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6626. // Promote to void*.
  6627. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6628. return destType;
  6629. }
  6630. return QualType();
  6631. }
  6632. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6633. /// ParenRange in parentheses.
  6634. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6635. const PartialDiagnostic &Note,
  6636. SourceRange ParenRange) {
  6637. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6638. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6639. EndLoc.isValid()) {
  6640. Self.Diag(Loc, Note)
  6641. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6642. << FixItHint::CreateInsertion(EndLoc, ")");
  6643. } else {
  6644. // We can't display the parentheses, so just show the bare note.
  6645. Self.Diag(Loc, Note) << ParenRange;
  6646. }
  6647. }
  6648. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6649. return BinaryOperator::isAdditiveOp(Opc) ||
  6650. BinaryOperator::isMultiplicativeOp(Opc) ||
  6651. BinaryOperator::isShiftOp(Opc);
  6652. }
  6653. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6654. /// expression, either using a built-in or overloaded operator,
  6655. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6656. /// expression.
  6657. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6658. Expr **RHSExprs) {
  6659. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6660. E = E->IgnoreImpCasts();
  6661. E = E->IgnoreConversionOperator();
  6662. E = E->IgnoreImpCasts();
  6663. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
  6664. E = MTE->GetTemporaryExpr();
  6665. E = E->IgnoreImpCasts();
  6666. }
  6667. // Built-in binary operator.
  6668. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6669. if (IsArithmeticOp(OP->getOpcode())) {
  6670. *Opcode = OP->getOpcode();
  6671. *RHSExprs = OP->getRHS();
  6672. return true;
  6673. }
  6674. }
  6675. // Overloaded operator.
  6676. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6677. if (Call->getNumArgs() != 2)
  6678. return false;
  6679. // Make sure this is really a binary operator that is safe to pass into
  6680. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6681. OverloadedOperatorKind OO = Call->getOperator();
  6682. if (OO < OO_Plus || OO > OO_Arrow ||
  6683. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6684. return false;
  6685. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6686. if (IsArithmeticOp(OpKind)) {
  6687. *Opcode = OpKind;
  6688. *RHSExprs = Call->getArg(1);
  6689. return true;
  6690. }
  6691. }
  6692. return false;
  6693. }
  6694. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6695. /// or is a logical expression such as (x==y) which has int type, but is
  6696. /// commonly interpreted as boolean.
  6697. static bool ExprLooksBoolean(Expr *E) {
  6698. E = E->IgnoreParenImpCasts();
  6699. if (E->getType()->isBooleanType())
  6700. return true;
  6701. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6702. return OP->isComparisonOp() || OP->isLogicalOp();
  6703. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6704. return OP->getOpcode() == UO_LNot;
  6705. if (E->getType()->isPointerType())
  6706. return true;
  6707. // FIXME: What about overloaded operator calls returning "unspecified boolean
  6708. // type"s (commonly pointer-to-members)?
  6709. return false;
  6710. }
  6711. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6712. /// and binary operator are mixed in a way that suggests the programmer assumed
  6713. /// the conditional operator has higher precedence, for example:
  6714. /// "int x = a + someBinaryCondition ? 1 : 2".
  6715. static void DiagnoseConditionalPrecedence(Sema &Self,
  6716. SourceLocation OpLoc,
  6717. Expr *Condition,
  6718. Expr *LHSExpr,
  6719. Expr *RHSExpr) {
  6720. BinaryOperatorKind CondOpcode;
  6721. Expr *CondRHS;
  6722. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6723. return;
  6724. if (!ExprLooksBoolean(CondRHS))
  6725. return;
  6726. // The condition is an arithmetic binary expression, with a right-
  6727. // hand side that looks boolean, so warn.
  6728. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6729. << Condition->getSourceRange()
  6730. << BinaryOperator::getOpcodeStr(CondOpcode);
  6731. SuggestParentheses(
  6732. Self, OpLoc,
  6733. Self.PDiag(diag::note_precedence_silence)
  6734. << BinaryOperator::getOpcodeStr(CondOpcode),
  6735. SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
  6736. SuggestParentheses(Self, OpLoc,
  6737. Self.PDiag(diag::note_precedence_conditional_first),
  6738. SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
  6739. }
  6740. /// Compute the nullability of a conditional expression.
  6741. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6742. QualType LHSTy, QualType RHSTy,
  6743. ASTContext &Ctx) {
  6744. if (!ResTy->isAnyPointerType())
  6745. return ResTy;
  6746. auto GetNullability = [&Ctx](QualType Ty) {
  6747. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6748. if (Kind)
  6749. return *Kind;
  6750. return NullabilityKind::Unspecified;
  6751. };
  6752. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6753. NullabilityKind MergedKind;
  6754. // Compute nullability of a binary conditional expression.
  6755. if (IsBin) {
  6756. if (LHSKind == NullabilityKind::NonNull)
  6757. MergedKind = NullabilityKind::NonNull;
  6758. else
  6759. MergedKind = RHSKind;
  6760. // Compute nullability of a normal conditional expression.
  6761. } else {
  6762. if (LHSKind == NullabilityKind::Nullable ||
  6763. RHSKind == NullabilityKind::Nullable)
  6764. MergedKind = NullabilityKind::Nullable;
  6765. else if (LHSKind == NullabilityKind::NonNull)
  6766. MergedKind = RHSKind;
  6767. else if (RHSKind == NullabilityKind::NonNull)
  6768. MergedKind = LHSKind;
  6769. else
  6770. MergedKind = NullabilityKind::Unspecified;
  6771. }
  6772. // Return if ResTy already has the correct nullability.
  6773. if (GetNullability(ResTy) == MergedKind)
  6774. return ResTy;
  6775. // Strip all nullability from ResTy.
  6776. while (ResTy->getNullability(Ctx))
  6777. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6778. // Create a new AttributedType with the new nullability kind.
  6779. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6780. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6781. }
  6782. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6783. /// in the case of a the GNU conditional expr extension.
  6784. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6785. SourceLocation ColonLoc,
  6786. Expr *CondExpr, Expr *LHSExpr,
  6787. Expr *RHSExpr) {
  6788. if (!getLangOpts().CPlusPlus) {
  6789. // C cannot handle TypoExpr nodes in the condition because it
  6790. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6791. // been dealt with before checking the operands.
  6792. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6793. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6794. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6795. if (!CondResult.isUsable())
  6796. return ExprError();
  6797. if (LHSExpr) {
  6798. if (!LHSResult.isUsable())
  6799. return ExprError();
  6800. }
  6801. if (!RHSResult.isUsable())
  6802. return ExprError();
  6803. CondExpr = CondResult.get();
  6804. LHSExpr = LHSResult.get();
  6805. RHSExpr = RHSResult.get();
  6806. }
  6807. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6808. // was the condition.
  6809. OpaqueValueExpr *opaqueValue = nullptr;
  6810. Expr *commonExpr = nullptr;
  6811. if (!LHSExpr) {
  6812. commonExpr = CondExpr;
  6813. // Lower out placeholder types first. This is important so that we don't
  6814. // try to capture a placeholder. This happens in few cases in C++; such
  6815. // as Objective-C++'s dictionary subscripting syntax.
  6816. if (commonExpr->hasPlaceholderType()) {
  6817. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6818. if (!result.isUsable()) return ExprError();
  6819. commonExpr = result.get();
  6820. }
  6821. // We usually want to apply unary conversions *before* saving, except
  6822. // in the special case of a C++ l-value conditional.
  6823. if (!(getLangOpts().CPlusPlus
  6824. && !commonExpr->isTypeDependent()
  6825. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6826. && commonExpr->isGLValue()
  6827. && commonExpr->isOrdinaryOrBitFieldObject()
  6828. && RHSExpr->isOrdinaryOrBitFieldObject()
  6829. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6830. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6831. if (commonRes.isInvalid())
  6832. return ExprError();
  6833. commonExpr = commonRes.get();
  6834. }
  6835. // If the common expression is a class or array prvalue, materialize it
  6836. // so that we can safely refer to it multiple times.
  6837. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6838. commonExpr->getType()->isArrayType())) {
  6839. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6840. if (MatExpr.isInvalid())
  6841. return ExprError();
  6842. commonExpr = MatExpr.get();
  6843. }
  6844. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6845. commonExpr->getType(),
  6846. commonExpr->getValueKind(),
  6847. commonExpr->getObjectKind(),
  6848. commonExpr);
  6849. LHSExpr = CondExpr = opaqueValue;
  6850. }
  6851. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6852. ExprValueKind VK = VK_RValue;
  6853. ExprObjectKind OK = OK_Ordinary;
  6854. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6855. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6856. VK, OK, QuestionLoc);
  6857. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6858. RHS.isInvalid())
  6859. return ExprError();
  6860. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6861. RHS.get());
  6862. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6863. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6864. Context);
  6865. if (!commonExpr)
  6866. return new (Context)
  6867. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6868. RHS.get(), result, VK, OK);
  6869. return new (Context) BinaryConditionalOperator(
  6870. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6871. ColonLoc, result, VK, OK);
  6872. }
  6873. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6874. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6875. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6876. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6877. // FIXME: add a couple examples in this comment.
  6878. static Sema::AssignConvertType
  6879. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6880. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6881. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6882. // get the "pointed to" type (ignoring qualifiers at the top level)
  6883. const Type *lhptee, *rhptee;
  6884. Qualifiers lhq, rhq;
  6885. std::tie(lhptee, lhq) =
  6886. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6887. std::tie(rhptee, rhq) =
  6888. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6889. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6890. // C99 6.5.16.1p1: This following citation is common to constraints
  6891. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6892. // qualifiers of the type *pointed to* by the right;
  6893. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6894. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6895. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6896. // Ignore lifetime for further calculation.
  6897. lhq.removeObjCLifetime();
  6898. rhq.removeObjCLifetime();
  6899. }
  6900. if (!lhq.compatiblyIncludes(rhq)) {
  6901. // Treat address-space mismatches as fatal.
  6902. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6903. return Sema::IncompatiblePointerDiscardsQualifiers;
  6904. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6905. // and from void*.
  6906. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6907. .compatiblyIncludes(
  6908. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6909. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6910. ; // keep old
  6911. // Treat lifetime mismatches as fatal.
  6912. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6913. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6914. // For GCC/MS compatibility, other qualifier mismatches are treated
  6915. // as still compatible in C.
  6916. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6917. }
  6918. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6919. // incomplete type and the other is a pointer to a qualified or unqualified
  6920. // version of void...
  6921. if (lhptee->isVoidType()) {
  6922. if (rhptee->isIncompleteOrObjectType())
  6923. return ConvTy;
  6924. // As an extension, we allow cast to/from void* to function pointer.
  6925. assert(rhptee->isFunctionType());
  6926. return Sema::FunctionVoidPointer;
  6927. }
  6928. if (rhptee->isVoidType()) {
  6929. if (lhptee->isIncompleteOrObjectType())
  6930. return ConvTy;
  6931. // As an extension, we allow cast to/from void* to function pointer.
  6932. assert(lhptee->isFunctionType());
  6933. return Sema::FunctionVoidPointer;
  6934. }
  6935. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6936. // unqualified versions of compatible types, ...
  6937. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6938. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6939. // Check if the pointee types are compatible ignoring the sign.
  6940. // We explicitly check for char so that we catch "char" vs
  6941. // "unsigned char" on systems where "char" is unsigned.
  6942. if (lhptee->isCharType())
  6943. ltrans = S.Context.UnsignedCharTy;
  6944. else if (lhptee->hasSignedIntegerRepresentation())
  6945. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6946. if (rhptee->isCharType())
  6947. rtrans = S.Context.UnsignedCharTy;
  6948. else if (rhptee->hasSignedIntegerRepresentation())
  6949. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6950. if (ltrans == rtrans) {
  6951. // Types are compatible ignoring the sign. Qualifier incompatibility
  6952. // takes priority over sign incompatibility because the sign
  6953. // warning can be disabled.
  6954. if (ConvTy != Sema::Compatible)
  6955. return ConvTy;
  6956. return Sema::IncompatiblePointerSign;
  6957. }
  6958. // If we are a multi-level pointer, it's possible that our issue is simply
  6959. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6960. // the eventual target type is the same and the pointers have the same
  6961. // level of indirection, this must be the issue.
  6962. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6963. do {
  6964. std::tie(lhptee, lhq) =
  6965. cast<PointerType>(lhptee)->getPointeeType().split().asPair();
  6966. std::tie(rhptee, rhq) =
  6967. cast<PointerType>(rhptee)->getPointeeType().split().asPair();
  6968. // Inconsistent address spaces at this point is invalid, even if the
  6969. // address spaces would be compatible.
  6970. // FIXME: This doesn't catch address space mismatches for pointers of
  6971. // different nesting levels, like:
  6972. // __local int *** a;
  6973. // int ** b = a;
  6974. // It's not clear how to actually determine when such pointers are
  6975. // invalidly incompatible.
  6976. if (lhq.getAddressSpace() != rhq.getAddressSpace())
  6977. return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
  6978. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6979. if (lhptee == rhptee)
  6980. return Sema::IncompatibleNestedPointerQualifiers;
  6981. }
  6982. // General pointer incompatibility takes priority over qualifiers.
  6983. return Sema::IncompatiblePointer;
  6984. }
  6985. if (!S.getLangOpts().CPlusPlus &&
  6986. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  6987. return Sema::IncompatiblePointer;
  6988. return ConvTy;
  6989. }
  6990. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6991. /// block pointer types are compatible or whether a block and normal pointer
  6992. /// are compatible. It is more restrict than comparing two function pointer
  6993. // types.
  6994. static Sema::AssignConvertType
  6995. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6996. QualType RHSType) {
  6997. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6998. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6999. QualType lhptee, rhptee;
  7000. // get the "pointed to" type (ignoring qualifiers at the top level)
  7001. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  7002. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  7003. // In C++, the types have to match exactly.
  7004. if (S.getLangOpts().CPlusPlus)
  7005. return Sema::IncompatibleBlockPointer;
  7006. Sema::AssignConvertType ConvTy = Sema::Compatible;
  7007. // For blocks we enforce that qualifiers are identical.
  7008. Qualifiers LQuals = lhptee.getLocalQualifiers();
  7009. Qualifiers RQuals = rhptee.getLocalQualifiers();
  7010. if (S.getLangOpts().OpenCL) {
  7011. LQuals.removeAddressSpace();
  7012. RQuals.removeAddressSpace();
  7013. }
  7014. if (LQuals != RQuals)
  7015. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  7016. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  7017. // assignment.
  7018. // The current behavior is similar to C++ lambdas. A block might be
  7019. // assigned to a variable iff its return type and parameters are compatible
  7020. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  7021. // an assignment. Presumably it should behave in way that a function pointer
  7022. // assignment does in C, so for each parameter and return type:
  7023. // * CVR and address space of LHS should be a superset of CVR and address
  7024. // space of RHS.
  7025. // * unqualified types should be compatible.
  7026. if (S.getLangOpts().OpenCL) {
  7027. if (!S.Context.typesAreBlockPointerCompatible(
  7028. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  7029. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  7030. return Sema::IncompatibleBlockPointer;
  7031. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  7032. return Sema::IncompatibleBlockPointer;
  7033. return ConvTy;
  7034. }
  7035. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  7036. /// for assignment compatibility.
  7037. static Sema::AssignConvertType
  7038. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  7039. QualType RHSType) {
  7040. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  7041. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  7042. if (LHSType->isObjCBuiltinType()) {
  7043. // Class is not compatible with ObjC object pointers.
  7044. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  7045. !RHSType->isObjCQualifiedClassType())
  7046. return Sema::IncompatiblePointer;
  7047. return Sema::Compatible;
  7048. }
  7049. if (RHSType->isObjCBuiltinType()) {
  7050. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  7051. !LHSType->isObjCQualifiedClassType())
  7052. return Sema::IncompatiblePointer;
  7053. return Sema::Compatible;
  7054. }
  7055. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  7056. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  7057. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  7058. // make an exception for id<P>
  7059. !LHSType->isObjCQualifiedIdType())
  7060. return Sema::CompatiblePointerDiscardsQualifiers;
  7061. if (S.Context.typesAreCompatible(LHSType, RHSType))
  7062. return Sema::Compatible;
  7063. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  7064. return Sema::IncompatibleObjCQualifiedId;
  7065. return Sema::IncompatiblePointer;
  7066. }
  7067. Sema::AssignConvertType
  7068. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  7069. QualType LHSType, QualType RHSType) {
  7070. // Fake up an opaque expression. We don't actually care about what
  7071. // cast operations are required, so if CheckAssignmentConstraints
  7072. // adds casts to this they'll be wasted, but fortunately that doesn't
  7073. // usually happen on valid code.
  7074. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  7075. ExprResult RHSPtr = &RHSExpr;
  7076. CastKind K;
  7077. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  7078. }
  7079. /// This helper function returns true if QT is a vector type that has element
  7080. /// type ElementType.
  7081. static bool isVector(QualType QT, QualType ElementType) {
  7082. if (const VectorType *VT = QT->getAs<VectorType>())
  7083. return VT->getElementType() == ElementType;
  7084. return false;
  7085. }
  7086. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  7087. /// has code to accommodate several GCC extensions when type checking
  7088. /// pointers. Here are some objectionable examples that GCC considers warnings:
  7089. ///
  7090. /// int a, *pint;
  7091. /// short *pshort;
  7092. /// struct foo *pfoo;
  7093. ///
  7094. /// pint = pshort; // warning: assignment from incompatible pointer type
  7095. /// a = pint; // warning: assignment makes integer from pointer without a cast
  7096. /// pint = a; // warning: assignment makes pointer from integer without a cast
  7097. /// pint = pfoo; // warning: assignment from incompatible pointer type
  7098. ///
  7099. /// As a result, the code for dealing with pointers is more complex than the
  7100. /// C99 spec dictates.
  7101. ///
  7102. /// Sets 'Kind' for any result kind except Incompatible.
  7103. Sema::AssignConvertType
  7104. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  7105. CastKind &Kind, bool ConvertRHS) {
  7106. QualType RHSType = RHS.get()->getType();
  7107. QualType OrigLHSType = LHSType;
  7108. // Get canonical types. We're not formatting these types, just comparing
  7109. // them.
  7110. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  7111. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  7112. // Common case: no conversion required.
  7113. if (LHSType == RHSType) {
  7114. Kind = CK_NoOp;
  7115. return Compatible;
  7116. }
  7117. // If we have an atomic type, try a non-atomic assignment, then just add an
  7118. // atomic qualification step.
  7119. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  7120. Sema::AssignConvertType result =
  7121. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  7122. if (result != Compatible)
  7123. return result;
  7124. if (Kind != CK_NoOp && ConvertRHS)
  7125. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  7126. Kind = CK_NonAtomicToAtomic;
  7127. return Compatible;
  7128. }
  7129. // If the left-hand side is a reference type, then we are in a
  7130. // (rare!) case where we've allowed the use of references in C,
  7131. // e.g., as a parameter type in a built-in function. In this case,
  7132. // just make sure that the type referenced is compatible with the
  7133. // right-hand side type. The caller is responsible for adjusting
  7134. // LHSType so that the resulting expression does not have reference
  7135. // type.
  7136. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  7137. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  7138. Kind = CK_LValueBitCast;
  7139. return Compatible;
  7140. }
  7141. return Incompatible;
  7142. }
  7143. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  7144. // to the same ExtVector type.
  7145. if (LHSType->isExtVectorType()) {
  7146. if (RHSType->isExtVectorType())
  7147. return Incompatible;
  7148. if (RHSType->isArithmeticType()) {
  7149. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  7150. if (ConvertRHS)
  7151. RHS = prepareVectorSplat(LHSType, RHS.get());
  7152. Kind = CK_VectorSplat;
  7153. return Compatible;
  7154. }
  7155. }
  7156. // Conversions to or from vector type.
  7157. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  7158. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  7159. // Allow assignments of an AltiVec vector type to an equivalent GCC
  7160. // vector type and vice versa
  7161. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7162. Kind = CK_BitCast;
  7163. return Compatible;
  7164. }
  7165. // If we are allowing lax vector conversions, and LHS and RHS are both
  7166. // vectors, the total size only needs to be the same. This is a bitcast;
  7167. // no bits are changed but the result type is different.
  7168. if (isLaxVectorConversion(RHSType, LHSType)) {
  7169. Kind = CK_BitCast;
  7170. return IncompatibleVectors;
  7171. }
  7172. }
  7173. // When the RHS comes from another lax conversion (e.g. binops between
  7174. // scalars and vectors) the result is canonicalized as a vector. When the
  7175. // LHS is also a vector, the lax is allowed by the condition above. Handle
  7176. // the case where LHS is a scalar.
  7177. if (LHSType->isScalarType()) {
  7178. const VectorType *VecType = RHSType->getAs<VectorType>();
  7179. if (VecType && VecType->getNumElements() == 1 &&
  7180. isLaxVectorConversion(RHSType, LHSType)) {
  7181. ExprResult *VecExpr = &RHS;
  7182. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  7183. Kind = CK_BitCast;
  7184. return Compatible;
  7185. }
  7186. }
  7187. return Incompatible;
  7188. }
  7189. // Diagnose attempts to convert between __float128 and long double where
  7190. // such conversions currently can't be handled.
  7191. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  7192. return Incompatible;
  7193. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  7194. // discards the imaginary part.
  7195. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  7196. !LHSType->getAs<ComplexType>())
  7197. return Incompatible;
  7198. // Arithmetic conversions.
  7199. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  7200. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  7201. if (ConvertRHS)
  7202. Kind = PrepareScalarCast(RHS, LHSType);
  7203. return Compatible;
  7204. }
  7205. // Conversions to normal pointers.
  7206. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  7207. // U* -> T*
  7208. if (isa<PointerType>(RHSType)) {
  7209. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7210. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  7211. if (AddrSpaceL != AddrSpaceR)
  7212. Kind = CK_AddressSpaceConversion;
  7213. else if (Context.hasCvrSimilarType(RHSType, LHSType))
  7214. Kind = CK_NoOp;
  7215. else
  7216. Kind = CK_BitCast;
  7217. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  7218. }
  7219. // int -> T*
  7220. if (RHSType->isIntegerType()) {
  7221. Kind = CK_IntegralToPointer; // FIXME: null?
  7222. return IntToPointer;
  7223. }
  7224. // C pointers are not compatible with ObjC object pointers,
  7225. // with two exceptions:
  7226. if (isa<ObjCObjectPointerType>(RHSType)) {
  7227. // - conversions to void*
  7228. if (LHSPointer->getPointeeType()->isVoidType()) {
  7229. Kind = CK_BitCast;
  7230. return Compatible;
  7231. }
  7232. // - conversions from 'Class' to the redefinition type
  7233. if (RHSType->isObjCClassType() &&
  7234. Context.hasSameType(LHSType,
  7235. Context.getObjCClassRedefinitionType())) {
  7236. Kind = CK_BitCast;
  7237. return Compatible;
  7238. }
  7239. Kind = CK_BitCast;
  7240. return IncompatiblePointer;
  7241. }
  7242. // U^ -> void*
  7243. if (RHSType->getAs<BlockPointerType>()) {
  7244. if (LHSPointer->getPointeeType()->isVoidType()) {
  7245. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  7246. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7247. ->getPointeeType()
  7248. .getAddressSpace();
  7249. Kind =
  7250. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7251. return Compatible;
  7252. }
  7253. }
  7254. return Incompatible;
  7255. }
  7256. // Conversions to block pointers.
  7257. if (isa<BlockPointerType>(LHSType)) {
  7258. // U^ -> T^
  7259. if (RHSType->isBlockPointerType()) {
  7260. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  7261. ->getPointeeType()
  7262. .getAddressSpace();
  7263. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  7264. ->getPointeeType()
  7265. .getAddressSpace();
  7266. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  7267. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  7268. }
  7269. // int or null -> T^
  7270. if (RHSType->isIntegerType()) {
  7271. Kind = CK_IntegralToPointer; // FIXME: null
  7272. return IntToBlockPointer;
  7273. }
  7274. // id -> T^
  7275. if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
  7276. Kind = CK_AnyPointerToBlockPointerCast;
  7277. return Compatible;
  7278. }
  7279. // void* -> T^
  7280. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  7281. if (RHSPT->getPointeeType()->isVoidType()) {
  7282. Kind = CK_AnyPointerToBlockPointerCast;
  7283. return Compatible;
  7284. }
  7285. return Incompatible;
  7286. }
  7287. // Conversions to Objective-C pointers.
  7288. if (isa<ObjCObjectPointerType>(LHSType)) {
  7289. // A* -> B*
  7290. if (RHSType->isObjCObjectPointerType()) {
  7291. Kind = CK_BitCast;
  7292. Sema::AssignConvertType result =
  7293. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  7294. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7295. result == Compatible &&
  7296. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  7297. result = IncompatibleObjCWeakRef;
  7298. return result;
  7299. }
  7300. // int or null -> A*
  7301. if (RHSType->isIntegerType()) {
  7302. Kind = CK_IntegralToPointer; // FIXME: null
  7303. return IntToPointer;
  7304. }
  7305. // In general, C pointers are not compatible with ObjC object pointers,
  7306. // with two exceptions:
  7307. if (isa<PointerType>(RHSType)) {
  7308. Kind = CK_CPointerToObjCPointerCast;
  7309. // - conversions from 'void*'
  7310. if (RHSType->isVoidPointerType()) {
  7311. return Compatible;
  7312. }
  7313. // - conversions to 'Class' from its redefinition type
  7314. if (LHSType->isObjCClassType() &&
  7315. Context.hasSameType(RHSType,
  7316. Context.getObjCClassRedefinitionType())) {
  7317. return Compatible;
  7318. }
  7319. return IncompatiblePointer;
  7320. }
  7321. // Only under strict condition T^ is compatible with an Objective-C pointer.
  7322. if (RHSType->isBlockPointerType() &&
  7323. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  7324. if (ConvertRHS)
  7325. maybeExtendBlockObject(RHS);
  7326. Kind = CK_BlockPointerToObjCPointerCast;
  7327. return Compatible;
  7328. }
  7329. return Incompatible;
  7330. }
  7331. // Conversions from pointers that are not covered by the above.
  7332. if (isa<PointerType>(RHSType)) {
  7333. // T* -> _Bool
  7334. if (LHSType == Context.BoolTy) {
  7335. Kind = CK_PointerToBoolean;
  7336. return Compatible;
  7337. }
  7338. // T* -> int
  7339. if (LHSType->isIntegerType()) {
  7340. Kind = CK_PointerToIntegral;
  7341. return PointerToInt;
  7342. }
  7343. return Incompatible;
  7344. }
  7345. // Conversions from Objective-C pointers that are not covered by the above.
  7346. if (isa<ObjCObjectPointerType>(RHSType)) {
  7347. // T* -> _Bool
  7348. if (LHSType == Context.BoolTy) {
  7349. Kind = CK_PointerToBoolean;
  7350. return Compatible;
  7351. }
  7352. // T* -> int
  7353. if (LHSType->isIntegerType()) {
  7354. Kind = CK_PointerToIntegral;
  7355. return PointerToInt;
  7356. }
  7357. return Incompatible;
  7358. }
  7359. // struct A -> struct B
  7360. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  7361. if (Context.typesAreCompatible(LHSType, RHSType)) {
  7362. Kind = CK_NoOp;
  7363. return Compatible;
  7364. }
  7365. }
  7366. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  7367. Kind = CK_IntToOCLSampler;
  7368. return Compatible;
  7369. }
  7370. return Incompatible;
  7371. }
  7372. /// Constructs a transparent union from an expression that is
  7373. /// used to initialize the transparent union.
  7374. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  7375. ExprResult &EResult, QualType UnionType,
  7376. FieldDecl *Field) {
  7377. // Build an initializer list that designates the appropriate member
  7378. // of the transparent union.
  7379. Expr *E = EResult.get();
  7380. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  7381. E, SourceLocation());
  7382. Initializer->setType(UnionType);
  7383. Initializer->setInitializedFieldInUnion(Field);
  7384. // Build a compound literal constructing a value of the transparent
  7385. // union type from this initializer list.
  7386. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  7387. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  7388. VK_RValue, Initializer, false);
  7389. }
  7390. Sema::AssignConvertType
  7391. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  7392. ExprResult &RHS) {
  7393. QualType RHSType = RHS.get()->getType();
  7394. // If the ArgType is a Union type, we want to handle a potential
  7395. // transparent_union GCC extension.
  7396. const RecordType *UT = ArgType->getAsUnionType();
  7397. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  7398. return Incompatible;
  7399. // The field to initialize within the transparent union.
  7400. RecordDecl *UD = UT->getDecl();
  7401. FieldDecl *InitField = nullptr;
  7402. // It's compatible if the expression matches any of the fields.
  7403. for (auto *it : UD->fields()) {
  7404. if (it->getType()->isPointerType()) {
  7405. // If the transparent union contains a pointer type, we allow:
  7406. // 1) void pointer
  7407. // 2) null pointer constant
  7408. if (RHSType->isPointerType())
  7409. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  7410. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  7411. InitField = it;
  7412. break;
  7413. }
  7414. if (RHS.get()->isNullPointerConstant(Context,
  7415. Expr::NPC_ValueDependentIsNull)) {
  7416. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  7417. CK_NullToPointer);
  7418. InitField = it;
  7419. break;
  7420. }
  7421. }
  7422. CastKind Kind;
  7423. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  7424. == Compatible) {
  7425. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  7426. InitField = it;
  7427. break;
  7428. }
  7429. }
  7430. if (!InitField)
  7431. return Incompatible;
  7432. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  7433. return Compatible;
  7434. }
  7435. Sema::AssignConvertType
  7436. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  7437. bool Diagnose,
  7438. bool DiagnoseCFAudited,
  7439. bool ConvertRHS) {
  7440. // We need to be able to tell the caller whether we diagnosed a problem, if
  7441. // they ask us to issue diagnostics.
  7442. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  7443. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  7444. // we can't avoid *all* modifications at the moment, so we need some somewhere
  7445. // to put the updated value.
  7446. ExprResult LocalRHS = CallerRHS;
  7447. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  7448. if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
  7449. if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
  7450. if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
  7451. !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  7452. Diag(RHS.get()->getExprLoc(),
  7453. diag::warn_noderef_to_dereferenceable_pointer)
  7454. << RHS.get()->getSourceRange();
  7455. }
  7456. }
  7457. }
  7458. if (getLangOpts().CPlusPlus) {
  7459. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  7460. // C++ 5.17p3: If the left operand is not of class type, the
  7461. // expression is implicitly converted (C++ 4) to the
  7462. // cv-unqualified type of the left operand.
  7463. QualType RHSType = RHS.get()->getType();
  7464. if (Diagnose) {
  7465. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7466. AA_Assigning);
  7467. } else {
  7468. ImplicitConversionSequence ICS =
  7469. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7470. /*SuppressUserConversions=*/false,
  7471. /*AllowExplicit=*/false,
  7472. /*InOverloadResolution=*/false,
  7473. /*CStyle=*/false,
  7474. /*AllowObjCWritebackConversion=*/false);
  7475. if (ICS.isFailure())
  7476. return Incompatible;
  7477. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  7478. ICS, AA_Assigning);
  7479. }
  7480. if (RHS.isInvalid())
  7481. return Incompatible;
  7482. Sema::AssignConvertType result = Compatible;
  7483. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7484. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  7485. result = IncompatibleObjCWeakRef;
  7486. return result;
  7487. }
  7488. // FIXME: Currently, we fall through and treat C++ classes like C
  7489. // structures.
  7490. // FIXME: We also fall through for atomics; not sure what should
  7491. // happen there, though.
  7492. } else if (RHS.get()->getType() == Context.OverloadTy) {
  7493. // As a set of extensions to C, we support overloading on functions. These
  7494. // functions need to be resolved here.
  7495. DeclAccessPair DAP;
  7496. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  7497. RHS.get(), LHSType, /*Complain=*/false, DAP))
  7498. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  7499. else
  7500. return Incompatible;
  7501. }
  7502. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7503. // a null pointer constant.
  7504. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7505. LHSType->isBlockPointerType()) &&
  7506. RHS.get()->isNullPointerConstant(Context,
  7507. Expr::NPC_ValueDependentIsNull)) {
  7508. if (Diagnose || ConvertRHS) {
  7509. CastKind Kind;
  7510. CXXCastPath Path;
  7511. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7512. /*IgnoreBaseAccess=*/false, Diagnose);
  7513. if (ConvertRHS)
  7514. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7515. }
  7516. return Compatible;
  7517. }
  7518. // OpenCL queue_t type assignment.
  7519. if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
  7520. Context, Expr::NPC_ValueDependentIsNull)) {
  7521. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  7522. return Compatible;
  7523. }
  7524. // This check seems unnatural, however it is necessary to ensure the proper
  7525. // conversion of functions/arrays. If the conversion were done for all
  7526. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7527. // expressions that suppress this implicit conversion (&, sizeof).
  7528. //
  7529. // Suppress this for references: C++ 8.5.3p5.
  7530. if (!LHSType->isReferenceType()) {
  7531. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7532. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7533. if (RHS.isInvalid())
  7534. return Incompatible;
  7535. }
  7536. CastKind Kind;
  7537. Sema::AssignConvertType result =
  7538. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7539. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7540. // type of the assignment expression.
  7541. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7542. // so that we can use references in built-in functions even in C.
  7543. // The getNonReferenceType() call makes sure that the resulting expression
  7544. // does not have reference type.
  7545. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7546. QualType Ty = LHSType.getNonLValueExprType(Context);
  7547. Expr *E = RHS.get();
  7548. // Check for various Objective-C errors. If we are not reporting
  7549. // diagnostics and just checking for errors, e.g., during overload
  7550. // resolution, return Incompatible to indicate the failure.
  7551. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7552. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7553. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7554. if (!Diagnose)
  7555. return Incompatible;
  7556. }
  7557. if (getLangOpts().ObjC &&
  7558. (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
  7559. E->getType(), E, Diagnose) ||
  7560. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7561. if (!Diagnose)
  7562. return Incompatible;
  7563. // Replace the expression with a corrected version and continue so we
  7564. // can find further errors.
  7565. RHS = E;
  7566. return Compatible;
  7567. }
  7568. if (ConvertRHS)
  7569. RHS = ImpCastExprToType(E, Ty, Kind);
  7570. }
  7571. return result;
  7572. }
  7573. namespace {
  7574. /// The original operand to an operator, prior to the application of the usual
  7575. /// arithmetic conversions and converting the arguments of a builtin operator
  7576. /// candidate.
  7577. struct OriginalOperand {
  7578. explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
  7579. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
  7580. Op = MTE->GetTemporaryExpr();
  7581. if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
  7582. Op = BTE->getSubExpr();
  7583. if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
  7584. Orig = ICE->getSubExprAsWritten();
  7585. Conversion = ICE->getConversionFunction();
  7586. }
  7587. }
  7588. QualType getType() const { return Orig->getType(); }
  7589. Expr *Orig;
  7590. NamedDecl *Conversion;
  7591. };
  7592. }
  7593. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7594. ExprResult &RHS) {
  7595. OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
  7596. Diag(Loc, diag::err_typecheck_invalid_operands)
  7597. << OrigLHS.getType() << OrigRHS.getType()
  7598. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7599. // If a user-defined conversion was applied to either of the operands prior
  7600. // to applying the built-in operator rules, tell the user about it.
  7601. if (OrigLHS.Conversion) {
  7602. Diag(OrigLHS.Conversion->getLocation(),
  7603. diag::note_typecheck_invalid_operands_converted)
  7604. << 0 << LHS.get()->getType();
  7605. }
  7606. if (OrigRHS.Conversion) {
  7607. Diag(OrigRHS.Conversion->getLocation(),
  7608. diag::note_typecheck_invalid_operands_converted)
  7609. << 1 << RHS.get()->getType();
  7610. }
  7611. return QualType();
  7612. }
  7613. // Diagnose cases where a scalar was implicitly converted to a vector and
  7614. // diagnose the underlying types. Otherwise, diagnose the error
  7615. // as invalid vector logical operands for non-C++ cases.
  7616. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7617. ExprResult &RHS) {
  7618. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7619. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7620. bool LHSNatVec = LHSType->isVectorType();
  7621. bool RHSNatVec = RHSType->isVectorType();
  7622. if (!(LHSNatVec && RHSNatVec)) {
  7623. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7624. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7625. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7626. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7627. << Vector->getSourceRange();
  7628. return QualType();
  7629. }
  7630. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7631. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7632. << RHS.get()->getSourceRange();
  7633. return QualType();
  7634. }
  7635. /// Try to convert a value of non-vector type to a vector type by converting
  7636. /// the type to the element type of the vector and then performing a splat.
  7637. /// If the language is OpenCL, we only use conversions that promote scalar
  7638. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7639. /// for float->int.
  7640. ///
  7641. /// OpenCL V2.0 6.2.6.p2:
  7642. /// An error shall occur if any scalar operand type has greater rank
  7643. /// than the type of the vector element.
  7644. ///
  7645. /// \param scalar - if non-null, actually perform the conversions
  7646. /// \return true if the operation fails (but without diagnosing the failure)
  7647. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7648. QualType scalarTy,
  7649. QualType vectorEltTy,
  7650. QualType vectorTy,
  7651. unsigned &DiagID) {
  7652. // The conversion to apply to the scalar before splatting it,
  7653. // if necessary.
  7654. CastKind scalarCast = CK_NoOp;
  7655. if (vectorEltTy->isIntegralType(S.Context)) {
  7656. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7657. (scalarTy->isIntegerType() &&
  7658. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7659. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7660. return true;
  7661. }
  7662. if (!scalarTy->isIntegralType(S.Context))
  7663. return true;
  7664. scalarCast = CK_IntegralCast;
  7665. } else if (vectorEltTy->isRealFloatingType()) {
  7666. if (scalarTy->isRealFloatingType()) {
  7667. if (S.getLangOpts().OpenCL &&
  7668. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7669. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7670. return true;
  7671. }
  7672. scalarCast = CK_FloatingCast;
  7673. }
  7674. else if (scalarTy->isIntegralType(S.Context))
  7675. scalarCast = CK_IntegralToFloating;
  7676. else
  7677. return true;
  7678. } else {
  7679. return true;
  7680. }
  7681. // Adjust scalar if desired.
  7682. if (scalar) {
  7683. if (scalarCast != CK_NoOp)
  7684. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7685. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7686. }
  7687. return false;
  7688. }
  7689. /// Convert vector E to a vector with the same number of elements but different
  7690. /// element type.
  7691. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7692. const auto *VecTy = E->getType()->getAs<VectorType>();
  7693. assert(VecTy && "Expression E must be a vector");
  7694. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7695. VecTy->getNumElements(),
  7696. VecTy->getVectorKind());
  7697. // Look through the implicit cast. Return the subexpression if its type is
  7698. // NewVecTy.
  7699. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7700. if (ICE->getSubExpr()->getType() == NewVecTy)
  7701. return ICE->getSubExpr();
  7702. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7703. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7704. }
  7705. /// Test if a (constant) integer Int can be casted to another integer type
  7706. /// IntTy without losing precision.
  7707. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7708. QualType OtherIntTy) {
  7709. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7710. // Reject cases where the value of the Int is unknown as that would
  7711. // possibly cause truncation, but accept cases where the scalar can be
  7712. // demoted without loss of precision.
  7713. Expr::EvalResult EVResult;
  7714. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7715. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7716. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7717. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7718. if (CstInt) {
  7719. // If the scalar is constant and is of a higher order and has more active
  7720. // bits that the vector element type, reject it.
  7721. llvm::APSInt Result = EVResult.Val.getInt();
  7722. unsigned NumBits = IntSigned
  7723. ? (Result.isNegative() ? Result.getMinSignedBits()
  7724. : Result.getActiveBits())
  7725. : Result.getActiveBits();
  7726. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7727. return true;
  7728. // If the signedness of the scalar type and the vector element type
  7729. // differs and the number of bits is greater than that of the vector
  7730. // element reject it.
  7731. return (IntSigned != OtherIntSigned &&
  7732. NumBits > S.Context.getIntWidth(OtherIntTy));
  7733. }
  7734. // Reject cases where the value of the scalar is not constant and it's
  7735. // order is greater than that of the vector element type.
  7736. return (Order < 0);
  7737. }
  7738. /// Test if a (constant) integer Int can be casted to floating point type
  7739. /// FloatTy without losing precision.
  7740. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7741. QualType FloatTy) {
  7742. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7743. // Determine if the integer constant can be expressed as a floating point
  7744. // number of the appropriate type.
  7745. Expr::EvalResult EVResult;
  7746. bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
  7747. uint64_t Bits = 0;
  7748. if (CstInt) {
  7749. // Reject constants that would be truncated if they were converted to
  7750. // the floating point type. Test by simple to/from conversion.
  7751. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7752. // could be avoided if there was a convertFromAPInt method
  7753. // which could signal back if implicit truncation occurred.
  7754. llvm::APSInt Result = EVResult.Val.getInt();
  7755. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7756. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7757. llvm::APFloat::rmTowardZero);
  7758. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7759. !IntTy->hasSignedIntegerRepresentation());
  7760. bool Ignored = false;
  7761. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7762. &Ignored);
  7763. if (Result != ConvertBack)
  7764. return true;
  7765. } else {
  7766. // Reject types that cannot be fully encoded into the mantissa of
  7767. // the float.
  7768. Bits = S.Context.getTypeSize(IntTy);
  7769. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7770. S.Context.getFloatTypeSemantics(FloatTy));
  7771. if (Bits > FloatPrec)
  7772. return true;
  7773. }
  7774. return false;
  7775. }
  7776. /// Attempt to convert and splat Scalar into a vector whose types matches
  7777. /// Vector following GCC conversion rules. The rule is that implicit
  7778. /// conversion can occur when Scalar can be casted to match Vector's element
  7779. /// type without causing truncation of Scalar.
  7780. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7781. ExprResult *Vector) {
  7782. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7783. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7784. const VectorType *VT = VectorTy->getAs<VectorType>();
  7785. assert(!isa<ExtVectorType>(VT) &&
  7786. "ExtVectorTypes should not be handled here!");
  7787. QualType VectorEltTy = VT->getElementType();
  7788. // Reject cases where the vector element type or the scalar element type are
  7789. // not integral or floating point types.
  7790. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7791. return true;
  7792. // The conversion to apply to the scalar before splatting it,
  7793. // if necessary.
  7794. CastKind ScalarCast = CK_NoOp;
  7795. // Accept cases where the vector elements are integers and the scalar is
  7796. // an integer.
  7797. // FIXME: Notionally if the scalar was a floating point value with a precise
  7798. // integral representation, we could cast it to an appropriate integer
  7799. // type and then perform the rest of the checks here. GCC will perform
  7800. // this conversion in some cases as determined by the input language.
  7801. // We should accept it on a language independent basis.
  7802. if (VectorEltTy->isIntegralType(S.Context) &&
  7803. ScalarTy->isIntegralType(S.Context) &&
  7804. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7805. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7806. return true;
  7807. ScalarCast = CK_IntegralCast;
  7808. } else if (VectorEltTy->isRealFloatingType()) {
  7809. if (ScalarTy->isRealFloatingType()) {
  7810. // Reject cases where the scalar type is not a constant and has a higher
  7811. // Order than the vector element type.
  7812. llvm::APFloat Result(0.0);
  7813. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7814. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7815. if (!CstScalar && Order < 0)
  7816. return true;
  7817. // If the scalar cannot be safely casted to the vector element type,
  7818. // reject it.
  7819. if (CstScalar) {
  7820. bool Truncated = false;
  7821. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7822. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7823. if (Truncated)
  7824. return true;
  7825. }
  7826. ScalarCast = CK_FloatingCast;
  7827. } else if (ScalarTy->isIntegralType(S.Context)) {
  7828. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7829. return true;
  7830. ScalarCast = CK_IntegralToFloating;
  7831. } else
  7832. return true;
  7833. }
  7834. // Adjust scalar if desired.
  7835. if (Scalar) {
  7836. if (ScalarCast != CK_NoOp)
  7837. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7838. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7839. }
  7840. return false;
  7841. }
  7842. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7843. SourceLocation Loc, bool IsCompAssign,
  7844. bool AllowBothBool,
  7845. bool AllowBoolConversions) {
  7846. if (!IsCompAssign) {
  7847. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7848. if (LHS.isInvalid())
  7849. return QualType();
  7850. }
  7851. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7852. if (RHS.isInvalid())
  7853. return QualType();
  7854. // For conversion purposes, we ignore any qualifiers.
  7855. // For example, "const float" and "float" are equivalent.
  7856. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7857. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7858. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7859. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7860. assert(LHSVecType || RHSVecType);
  7861. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7862. // for some operators but not others.
  7863. if (!AllowBothBool &&
  7864. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7865. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7866. return InvalidOperands(Loc, LHS, RHS);
  7867. // If the vector types are identical, return.
  7868. if (Context.hasSameType(LHSType, RHSType))
  7869. return LHSType;
  7870. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7871. if (LHSVecType && RHSVecType &&
  7872. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7873. if (isa<ExtVectorType>(LHSVecType)) {
  7874. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7875. return LHSType;
  7876. }
  7877. if (!IsCompAssign)
  7878. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7879. return RHSType;
  7880. }
  7881. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7882. // can be mixed, with the result being the non-bool type. The non-bool
  7883. // operand must have integer element type.
  7884. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7885. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7886. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7887. Context.getTypeSize(RHSVecType->getElementType()))) {
  7888. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7889. LHSVecType->getElementType()->isIntegerType() &&
  7890. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7891. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7892. return LHSType;
  7893. }
  7894. if (!IsCompAssign &&
  7895. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7896. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7897. RHSVecType->getElementType()->isIntegerType()) {
  7898. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7899. return RHSType;
  7900. }
  7901. }
  7902. // If there's a vector type and a scalar, try to convert the scalar to
  7903. // the vector element type and splat.
  7904. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7905. if (!RHSVecType) {
  7906. if (isa<ExtVectorType>(LHSVecType)) {
  7907. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7908. LHSVecType->getElementType(), LHSType,
  7909. DiagID))
  7910. return LHSType;
  7911. } else {
  7912. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7913. return LHSType;
  7914. }
  7915. }
  7916. if (!LHSVecType) {
  7917. if (isa<ExtVectorType>(RHSVecType)) {
  7918. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7919. LHSType, RHSVecType->getElementType(),
  7920. RHSType, DiagID))
  7921. return RHSType;
  7922. } else {
  7923. if (LHS.get()->getValueKind() == VK_LValue ||
  7924. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7925. return RHSType;
  7926. }
  7927. }
  7928. // FIXME: The code below also handles conversion between vectors and
  7929. // non-scalars, we should break this down into fine grained specific checks
  7930. // and emit proper diagnostics.
  7931. QualType VecType = LHSVecType ? LHSType : RHSType;
  7932. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7933. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7934. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7935. if (isLaxVectorConversion(OtherType, VecType)) {
  7936. // If we're allowing lax vector conversions, only the total (data) size
  7937. // needs to be the same. For non compound assignment, if one of the types is
  7938. // scalar, the result is always the vector type.
  7939. if (!IsCompAssign) {
  7940. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7941. return VecType;
  7942. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7943. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7944. // type. Note that this is already done by non-compound assignments in
  7945. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7946. // <1 x T> -> T. The result is also a vector type.
  7947. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7948. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7949. ExprResult *RHSExpr = &RHS;
  7950. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7951. return VecType;
  7952. }
  7953. }
  7954. // Okay, the expression is invalid.
  7955. // If there's a non-vector, non-real operand, diagnose that.
  7956. if ((!RHSVecType && !RHSType->isRealType()) ||
  7957. (!LHSVecType && !LHSType->isRealType())) {
  7958. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7959. << LHSType << RHSType
  7960. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7961. return QualType();
  7962. }
  7963. // OpenCL V1.1 6.2.6.p1:
  7964. // If the operands are of more than one vector type, then an error shall
  7965. // occur. Implicit conversions between vector types are not permitted, per
  7966. // section 6.2.1.
  7967. if (getLangOpts().OpenCL &&
  7968. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7969. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7970. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7971. << RHSType;
  7972. return QualType();
  7973. }
  7974. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7975. // this point if scalar could not be converted to the vector's element type
  7976. // without truncation.
  7977. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7978. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7979. QualType Scalar = LHSVecType ? RHSType : LHSType;
  7980. QualType Vector = LHSVecType ? LHSType : RHSType;
  7981. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  7982. Diag(Loc,
  7983. diag::err_typecheck_vector_not_convertable_implict_truncation)
  7984. << ScalarOrVector << Scalar << Vector;
  7985. return QualType();
  7986. }
  7987. // Otherwise, use the generic diagnostic.
  7988. Diag(Loc, DiagID)
  7989. << LHSType << RHSType
  7990. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7991. return QualType();
  7992. }
  7993. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  7994. // expression. These are mainly cases where the null pointer is used as an
  7995. // integer instead of a pointer.
  7996. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7997. SourceLocation Loc, bool IsCompare) {
  7998. // The canonical way to check for a GNU null is with isNullPointerConstant,
  7999. // but we use a bit of a hack here for speed; this is a relatively
  8000. // hot path, and isNullPointerConstant is slow.
  8001. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  8002. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  8003. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  8004. // Avoid analyzing cases where the result will either be invalid (and
  8005. // diagnosed as such) or entirely valid and not something to warn about.
  8006. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  8007. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  8008. return;
  8009. // Comparison operations would not make sense with a null pointer no matter
  8010. // what the other expression is.
  8011. if (!IsCompare) {
  8012. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  8013. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  8014. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  8015. return;
  8016. }
  8017. // The rest of the operations only make sense with a null pointer
  8018. // if the other expression is a pointer.
  8019. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  8020. NonNullType->canDecayToPointerType())
  8021. return;
  8022. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  8023. << LHSNull /* LHS is NULL */ << NonNullType
  8024. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8025. }
  8026. static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
  8027. SourceLocation Loc) {
  8028. const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
  8029. const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
  8030. if (!LUE || !RUE)
  8031. return;
  8032. if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
  8033. RUE->getKind() != UETT_SizeOf)
  8034. return;
  8035. const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
  8036. QualType LHSTy = LHSArg->getType();
  8037. QualType RHSTy;
  8038. if (RUE->isArgumentType())
  8039. RHSTy = RUE->getArgumentType();
  8040. else
  8041. RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
  8042. if (!LHSTy->isPointerType() || RHSTy->isPointerType())
  8043. return;
  8044. if (LHSTy->getPointeeType().getCanonicalType() != RHSTy.getCanonicalType())
  8045. return;
  8046. S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
  8047. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
  8048. if (const ValueDecl *LHSArgDecl = DRE->getDecl())
  8049. S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
  8050. << LHSArgDecl;
  8051. }
  8052. }
  8053. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  8054. ExprResult &RHS,
  8055. SourceLocation Loc, bool IsDiv) {
  8056. // Check for division/remainder by zero.
  8057. Expr::EvalResult RHSValue;
  8058. if (!RHS.get()->isValueDependent() &&
  8059. RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
  8060. RHSValue.Val.getInt() == 0)
  8061. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8062. S.PDiag(diag::warn_remainder_division_by_zero)
  8063. << IsDiv << RHS.get()->getSourceRange());
  8064. }
  8065. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  8066. SourceLocation Loc,
  8067. bool IsCompAssign, bool IsDiv) {
  8068. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8069. if (LHS.get()->getType()->isVectorType() ||
  8070. RHS.get()->getType()->isVectorType())
  8071. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8072. /*AllowBothBool*/getLangOpts().AltiVec,
  8073. /*AllowBoolConversions*/false);
  8074. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8075. if (LHS.isInvalid() || RHS.isInvalid())
  8076. return QualType();
  8077. if (compType.isNull() || !compType->isArithmeticType())
  8078. return InvalidOperands(Loc, LHS, RHS);
  8079. if (IsDiv) {
  8080. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  8081. DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
  8082. }
  8083. return compType;
  8084. }
  8085. QualType Sema::CheckRemainderOperands(
  8086. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  8087. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8088. if (LHS.get()->getType()->isVectorType() ||
  8089. RHS.get()->getType()->isVectorType()) {
  8090. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  8091. RHS.get()->getType()->hasIntegerRepresentation())
  8092. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8093. /*AllowBothBool*/getLangOpts().AltiVec,
  8094. /*AllowBoolConversions*/false);
  8095. return InvalidOperands(Loc, LHS, RHS);
  8096. }
  8097. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  8098. if (LHS.isInvalid() || RHS.isInvalid())
  8099. return QualType();
  8100. if (compType.isNull() || !compType->isIntegerType())
  8101. return InvalidOperands(Loc, LHS, RHS);
  8102. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  8103. return compType;
  8104. }
  8105. /// Diagnose invalid arithmetic on two void pointers.
  8106. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  8107. Expr *LHSExpr, Expr *RHSExpr) {
  8108. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8109. ? diag::err_typecheck_pointer_arith_void_type
  8110. : diag::ext_gnu_void_ptr)
  8111. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  8112. << RHSExpr->getSourceRange();
  8113. }
  8114. /// Diagnose invalid arithmetic on a void pointer.
  8115. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  8116. Expr *Pointer) {
  8117. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8118. ? diag::err_typecheck_pointer_arith_void_type
  8119. : diag::ext_gnu_void_ptr)
  8120. << 0 /* one pointer */ << Pointer->getSourceRange();
  8121. }
  8122. /// Diagnose invalid arithmetic on a null pointer.
  8123. ///
  8124. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  8125. /// idiom, which we recognize as a GNU extension.
  8126. ///
  8127. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  8128. Expr *Pointer, bool IsGNUIdiom) {
  8129. if (IsGNUIdiom)
  8130. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  8131. << Pointer->getSourceRange();
  8132. else
  8133. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  8134. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  8135. }
  8136. /// Diagnose invalid arithmetic on two function pointers.
  8137. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  8138. Expr *LHS, Expr *RHS) {
  8139. assert(LHS->getType()->isAnyPointerType());
  8140. assert(RHS->getType()->isAnyPointerType());
  8141. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8142. ? diag::err_typecheck_pointer_arith_function_type
  8143. : diag::ext_gnu_ptr_func_arith)
  8144. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  8145. // We only show the second type if it differs from the first.
  8146. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  8147. RHS->getType())
  8148. << RHS->getType()->getPointeeType()
  8149. << LHS->getSourceRange() << RHS->getSourceRange();
  8150. }
  8151. /// Diagnose invalid arithmetic on a function pointer.
  8152. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  8153. Expr *Pointer) {
  8154. assert(Pointer->getType()->isAnyPointerType());
  8155. S.Diag(Loc, S.getLangOpts().CPlusPlus
  8156. ? diag::err_typecheck_pointer_arith_function_type
  8157. : diag::ext_gnu_ptr_func_arith)
  8158. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  8159. << 0 /* one pointer, so only one type */
  8160. << Pointer->getSourceRange();
  8161. }
  8162. /// Emit error if Operand is incomplete pointer type
  8163. ///
  8164. /// \returns True if pointer has incomplete type
  8165. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  8166. Expr *Operand) {
  8167. QualType ResType = Operand->getType();
  8168. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8169. ResType = ResAtomicType->getValueType();
  8170. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  8171. QualType PointeeTy = ResType->getPointeeType();
  8172. return S.RequireCompleteType(Loc, PointeeTy,
  8173. diag::err_typecheck_arithmetic_incomplete_type,
  8174. PointeeTy, Operand->getSourceRange());
  8175. }
  8176. /// Check the validity of an arithmetic pointer operand.
  8177. ///
  8178. /// If the operand has pointer type, this code will check for pointer types
  8179. /// which are invalid in arithmetic operations. These will be diagnosed
  8180. /// appropriately, including whether or not the use is supported as an
  8181. /// extension.
  8182. ///
  8183. /// \returns True when the operand is valid to use (even if as an extension).
  8184. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  8185. Expr *Operand) {
  8186. QualType ResType = Operand->getType();
  8187. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  8188. ResType = ResAtomicType->getValueType();
  8189. if (!ResType->isAnyPointerType()) return true;
  8190. QualType PointeeTy = ResType->getPointeeType();
  8191. if (PointeeTy->isVoidType()) {
  8192. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  8193. return !S.getLangOpts().CPlusPlus;
  8194. }
  8195. if (PointeeTy->isFunctionType()) {
  8196. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  8197. return !S.getLangOpts().CPlusPlus;
  8198. }
  8199. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  8200. return true;
  8201. }
  8202. /// Check the validity of a binary arithmetic operation w.r.t. pointer
  8203. /// operands.
  8204. ///
  8205. /// This routine will diagnose any invalid arithmetic on pointer operands much
  8206. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  8207. /// for emitting a single diagnostic even for operations where both LHS and RHS
  8208. /// are (potentially problematic) pointers.
  8209. ///
  8210. /// \returns True when the operand is valid to use (even if as an extension).
  8211. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  8212. Expr *LHSExpr, Expr *RHSExpr) {
  8213. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  8214. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  8215. if (!isLHSPointer && !isRHSPointer) return true;
  8216. QualType LHSPointeeTy, RHSPointeeTy;
  8217. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  8218. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  8219. // if both are pointers check if operation is valid wrt address spaces
  8220. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  8221. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  8222. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  8223. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  8224. S.Diag(Loc,
  8225. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8226. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  8227. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  8228. return false;
  8229. }
  8230. }
  8231. // Check for arithmetic on pointers to incomplete types.
  8232. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  8233. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  8234. if (isLHSVoidPtr || isRHSVoidPtr) {
  8235. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  8236. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  8237. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  8238. return !S.getLangOpts().CPlusPlus;
  8239. }
  8240. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  8241. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  8242. if (isLHSFuncPtr || isRHSFuncPtr) {
  8243. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  8244. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  8245. RHSExpr);
  8246. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  8247. return !S.getLangOpts().CPlusPlus;
  8248. }
  8249. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  8250. return false;
  8251. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  8252. return false;
  8253. return true;
  8254. }
  8255. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  8256. /// literal.
  8257. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  8258. Expr *LHSExpr, Expr *RHSExpr) {
  8259. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  8260. Expr* IndexExpr = RHSExpr;
  8261. if (!StrExpr) {
  8262. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  8263. IndexExpr = LHSExpr;
  8264. }
  8265. bool IsStringPlusInt = StrExpr &&
  8266. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  8267. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  8268. return;
  8269. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8270. Self.Diag(OpLoc, diag::warn_string_plus_int)
  8271. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  8272. // Only print a fixit for "str" + int, not for int + "str".
  8273. if (IndexExpr == RHSExpr) {
  8274. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8275. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8276. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8277. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8278. << FixItHint::CreateInsertion(EndLoc, "]");
  8279. } else
  8280. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8281. }
  8282. /// Emit a warning when adding a char literal to a string.
  8283. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  8284. Expr *LHSExpr, Expr *RHSExpr) {
  8285. const Expr *StringRefExpr = LHSExpr;
  8286. const CharacterLiteral *CharExpr =
  8287. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  8288. if (!CharExpr) {
  8289. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  8290. StringRefExpr = RHSExpr;
  8291. }
  8292. if (!CharExpr || !StringRefExpr)
  8293. return;
  8294. const QualType StringType = StringRefExpr->getType();
  8295. // Return if not a PointerType.
  8296. if (!StringType->isAnyPointerType())
  8297. return;
  8298. // Return if not a CharacterType.
  8299. if (!StringType->getPointeeType()->isAnyCharacterType())
  8300. return;
  8301. ASTContext &Ctx = Self.getASTContext();
  8302. SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  8303. const QualType CharType = CharExpr->getType();
  8304. if (!CharType->isAnyCharacterType() &&
  8305. CharType->isIntegerType() &&
  8306. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  8307. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8308. << DiagRange << Ctx.CharTy;
  8309. } else {
  8310. Self.Diag(OpLoc, diag::warn_string_plus_char)
  8311. << DiagRange << CharExpr->getType();
  8312. }
  8313. // Only print a fixit for str + char, not for char + str.
  8314. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  8315. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
  8316. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  8317. << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
  8318. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  8319. << FixItHint::CreateInsertion(EndLoc, "]");
  8320. } else {
  8321. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  8322. }
  8323. }
  8324. /// Emit error when two pointers are incompatible.
  8325. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  8326. Expr *LHSExpr, Expr *RHSExpr) {
  8327. assert(LHSExpr->getType()->isAnyPointerType());
  8328. assert(RHSExpr->getType()->isAnyPointerType());
  8329. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  8330. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  8331. << RHSExpr->getSourceRange();
  8332. }
  8333. // C99 6.5.6
  8334. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  8335. SourceLocation Loc, BinaryOperatorKind Opc,
  8336. QualType* CompLHSTy) {
  8337. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8338. if (LHS.get()->getType()->isVectorType() ||
  8339. RHS.get()->getType()->isVectorType()) {
  8340. QualType compType = CheckVectorOperands(
  8341. LHS, RHS, Loc, CompLHSTy,
  8342. /*AllowBothBool*/getLangOpts().AltiVec,
  8343. /*AllowBoolConversions*/getLangOpts().ZVector);
  8344. if (CompLHSTy) *CompLHSTy = compType;
  8345. return compType;
  8346. }
  8347. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8348. if (LHS.isInvalid() || RHS.isInvalid())
  8349. return QualType();
  8350. // Diagnose "string literal" '+' int and string '+' "char literal".
  8351. if (Opc == BO_Add) {
  8352. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  8353. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  8354. }
  8355. // handle the common case first (both operands are arithmetic).
  8356. if (!compType.isNull() && compType->isArithmeticType()) {
  8357. if (CompLHSTy) *CompLHSTy = compType;
  8358. return compType;
  8359. }
  8360. // Type-checking. Ultimately the pointer's going to be in PExp;
  8361. // note that we bias towards the LHS being the pointer.
  8362. Expr *PExp = LHS.get(), *IExp = RHS.get();
  8363. bool isObjCPointer;
  8364. if (PExp->getType()->isPointerType()) {
  8365. isObjCPointer = false;
  8366. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8367. isObjCPointer = true;
  8368. } else {
  8369. std::swap(PExp, IExp);
  8370. if (PExp->getType()->isPointerType()) {
  8371. isObjCPointer = false;
  8372. } else if (PExp->getType()->isObjCObjectPointerType()) {
  8373. isObjCPointer = true;
  8374. } else {
  8375. return InvalidOperands(Loc, LHS, RHS);
  8376. }
  8377. }
  8378. assert(PExp->getType()->isAnyPointerType());
  8379. if (!IExp->getType()->isIntegerType())
  8380. return InvalidOperands(Loc, LHS, RHS);
  8381. // Adding to a null pointer results in undefined behavior.
  8382. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  8383. Context, Expr::NPC_ValueDependentIsNotNull)) {
  8384. // In C++ adding zero to a null pointer is defined.
  8385. Expr::EvalResult KnownVal;
  8386. if (!getLangOpts().CPlusPlus ||
  8387. (!IExp->isValueDependent() &&
  8388. (!IExp->EvaluateAsInt(KnownVal, Context) ||
  8389. KnownVal.Val.getInt() != 0))) {
  8390. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  8391. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  8392. Context, BO_Add, PExp, IExp);
  8393. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  8394. }
  8395. }
  8396. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  8397. return QualType();
  8398. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  8399. return QualType();
  8400. // Check array bounds for pointer arithemtic
  8401. CheckArrayAccess(PExp, IExp);
  8402. if (CompLHSTy) {
  8403. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  8404. if (LHSTy.isNull()) {
  8405. LHSTy = LHS.get()->getType();
  8406. if (LHSTy->isPromotableIntegerType())
  8407. LHSTy = Context.getPromotedIntegerType(LHSTy);
  8408. }
  8409. *CompLHSTy = LHSTy;
  8410. }
  8411. return PExp->getType();
  8412. }
  8413. // C99 6.5.6
  8414. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  8415. SourceLocation Loc,
  8416. QualType* CompLHSTy) {
  8417. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8418. if (LHS.get()->getType()->isVectorType() ||
  8419. RHS.get()->getType()->isVectorType()) {
  8420. QualType compType = CheckVectorOperands(
  8421. LHS, RHS, Loc, CompLHSTy,
  8422. /*AllowBothBool*/getLangOpts().AltiVec,
  8423. /*AllowBoolConversions*/getLangOpts().ZVector);
  8424. if (CompLHSTy) *CompLHSTy = compType;
  8425. return compType;
  8426. }
  8427. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  8428. if (LHS.isInvalid() || RHS.isInvalid())
  8429. return QualType();
  8430. // Enforce type constraints: C99 6.5.6p3.
  8431. // Handle the common case first (both operands are arithmetic).
  8432. if (!compType.isNull() && compType->isArithmeticType()) {
  8433. if (CompLHSTy) *CompLHSTy = compType;
  8434. return compType;
  8435. }
  8436. // Either ptr - int or ptr - ptr.
  8437. if (LHS.get()->getType()->isAnyPointerType()) {
  8438. QualType lpointee = LHS.get()->getType()->getPointeeType();
  8439. // Diagnose bad cases where we step over interface counts.
  8440. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  8441. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  8442. return QualType();
  8443. // The result type of a pointer-int computation is the pointer type.
  8444. if (RHS.get()->getType()->isIntegerType()) {
  8445. // Subtracting from a null pointer should produce a warning.
  8446. // The last argument to the diagnose call says this doesn't match the
  8447. // GNU int-to-pointer idiom.
  8448. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  8449. Expr::NPC_ValueDependentIsNotNull)) {
  8450. // In C++ adding zero to a null pointer is defined.
  8451. Expr::EvalResult KnownVal;
  8452. if (!getLangOpts().CPlusPlus ||
  8453. (!RHS.get()->isValueDependent() &&
  8454. (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
  8455. KnownVal.Val.getInt() != 0))) {
  8456. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  8457. }
  8458. }
  8459. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  8460. return QualType();
  8461. // Check array bounds for pointer arithemtic
  8462. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  8463. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  8464. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8465. return LHS.get()->getType();
  8466. }
  8467. // Handle pointer-pointer subtractions.
  8468. if (const PointerType *RHSPTy
  8469. = RHS.get()->getType()->getAs<PointerType>()) {
  8470. QualType rpointee = RHSPTy->getPointeeType();
  8471. if (getLangOpts().CPlusPlus) {
  8472. // Pointee types must be the same: C++ [expr.add]
  8473. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  8474. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8475. }
  8476. } else {
  8477. // Pointee types must be compatible C99 6.5.6p3
  8478. if (!Context.typesAreCompatible(
  8479. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  8480. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  8481. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  8482. return QualType();
  8483. }
  8484. }
  8485. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  8486. LHS.get(), RHS.get()))
  8487. return QualType();
  8488. // FIXME: Add warnings for nullptr - ptr.
  8489. // The pointee type may have zero size. As an extension, a structure or
  8490. // union may have zero size or an array may have zero length. In this
  8491. // case subtraction does not make sense.
  8492. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  8493. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  8494. if (ElementSize.isZero()) {
  8495. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  8496. << rpointee.getUnqualifiedType()
  8497. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8498. }
  8499. }
  8500. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  8501. return Context.getPointerDiffType();
  8502. }
  8503. }
  8504. return InvalidOperands(Loc, LHS, RHS);
  8505. }
  8506. static bool isScopedEnumerationType(QualType T) {
  8507. if (const EnumType *ET = T->getAs<EnumType>())
  8508. return ET->getDecl()->isScoped();
  8509. return false;
  8510. }
  8511. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  8512. SourceLocation Loc, BinaryOperatorKind Opc,
  8513. QualType LHSType) {
  8514. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  8515. // so skip remaining warnings as we don't want to modify values within Sema.
  8516. if (S.getLangOpts().OpenCL)
  8517. return;
  8518. // Check right/shifter operand
  8519. Expr::EvalResult RHSResult;
  8520. if (RHS.get()->isValueDependent() ||
  8521. !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
  8522. return;
  8523. llvm::APSInt Right = RHSResult.Val.getInt();
  8524. if (Right.isNegative()) {
  8525. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8526. S.PDiag(diag::warn_shift_negative)
  8527. << RHS.get()->getSourceRange());
  8528. return;
  8529. }
  8530. llvm::APInt LeftBits(Right.getBitWidth(),
  8531. S.Context.getTypeSize(LHS.get()->getType()));
  8532. if (Right.uge(LeftBits)) {
  8533. S.DiagRuntimeBehavior(Loc, RHS.get(),
  8534. S.PDiag(diag::warn_shift_gt_typewidth)
  8535. << RHS.get()->getSourceRange());
  8536. return;
  8537. }
  8538. if (Opc != BO_Shl)
  8539. return;
  8540. // When left shifting an ICE which is signed, we can check for overflow which
  8541. // according to C++ standards prior to C++2a has undefined behavior
  8542. // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
  8543. // more than the maximum value representable in the result type, so never
  8544. // warn for those. (FIXME: Unsigned left-shift overflow in a constant
  8545. // expression is still probably a bug.)
  8546. Expr::EvalResult LHSResult;
  8547. if (LHS.get()->isValueDependent() ||
  8548. LHSType->hasUnsignedIntegerRepresentation() ||
  8549. !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
  8550. return;
  8551. llvm::APSInt Left = LHSResult.Val.getInt();
  8552. // If LHS does not have a signed type and non-negative value
  8553. // then, the behavior is undefined before C++2a. Warn about it.
  8554. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
  8555. !S.getLangOpts().CPlusPlus2a) {
  8556. S.DiagRuntimeBehavior(Loc, LHS.get(),
  8557. S.PDiag(diag::warn_shift_lhs_negative)
  8558. << LHS.get()->getSourceRange());
  8559. return;
  8560. }
  8561. llvm::APInt ResultBits =
  8562. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  8563. if (LeftBits.uge(ResultBits))
  8564. return;
  8565. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8566. Result = Result.shl(Right);
  8567. // Print the bit representation of the signed integer as an unsigned
  8568. // hexadecimal number.
  8569. SmallString<40> HexResult;
  8570. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8571. // If we are only missing a sign bit, this is less likely to result in actual
  8572. // bugs -- if the result is cast back to an unsigned type, it will have the
  8573. // expected value. Thus we place this behind a different warning that can be
  8574. // turned off separately if needed.
  8575. if (LeftBits == ResultBits - 1) {
  8576. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8577. << HexResult << LHSType
  8578. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8579. return;
  8580. }
  8581. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8582. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8583. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8584. << RHS.get()->getSourceRange();
  8585. }
  8586. /// Return the resulting type when a vector is shifted
  8587. /// by a scalar or vector shift amount.
  8588. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8589. SourceLocation Loc, bool IsCompAssign) {
  8590. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8591. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8592. !LHS.get()->getType()->isVectorType()) {
  8593. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8594. << RHS.get()->getType() << LHS.get()->getType()
  8595. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8596. return QualType();
  8597. }
  8598. if (!IsCompAssign) {
  8599. LHS = S.UsualUnaryConversions(LHS.get());
  8600. if (LHS.isInvalid()) return QualType();
  8601. }
  8602. RHS = S.UsualUnaryConversions(RHS.get());
  8603. if (RHS.isInvalid()) return QualType();
  8604. QualType LHSType = LHS.get()->getType();
  8605. // Note that LHS might be a scalar because the routine calls not only in
  8606. // OpenCL case.
  8607. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8608. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8609. // Note that RHS might not be a vector.
  8610. QualType RHSType = RHS.get()->getType();
  8611. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8612. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8613. // The operands need to be integers.
  8614. if (!LHSEleType->isIntegerType()) {
  8615. S.Diag(Loc, diag::err_typecheck_expect_int)
  8616. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8617. return QualType();
  8618. }
  8619. if (!RHSEleType->isIntegerType()) {
  8620. S.Diag(Loc, diag::err_typecheck_expect_int)
  8621. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8622. return QualType();
  8623. }
  8624. if (!LHSVecTy) {
  8625. assert(RHSVecTy);
  8626. if (IsCompAssign)
  8627. return RHSType;
  8628. if (LHSEleType != RHSEleType) {
  8629. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8630. LHSEleType = RHSEleType;
  8631. }
  8632. QualType VecTy =
  8633. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8634. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8635. LHSType = VecTy;
  8636. } else if (RHSVecTy) {
  8637. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8638. // are applied component-wise. So if RHS is a vector, then ensure
  8639. // that the number of elements is the same as LHS...
  8640. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8641. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8642. << LHS.get()->getType() << RHS.get()->getType()
  8643. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8644. return QualType();
  8645. }
  8646. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8647. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8648. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8649. if (LHSBT != RHSBT &&
  8650. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8651. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8652. << LHS.get()->getType() << RHS.get()->getType()
  8653. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8654. }
  8655. }
  8656. } else {
  8657. // ...else expand RHS to match the number of elements in LHS.
  8658. QualType VecTy =
  8659. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8660. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8661. }
  8662. return LHSType;
  8663. }
  8664. // C99 6.5.7
  8665. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8666. SourceLocation Loc, BinaryOperatorKind Opc,
  8667. bool IsCompAssign) {
  8668. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  8669. // Vector shifts promote their scalar inputs to vector type.
  8670. if (LHS.get()->getType()->isVectorType() ||
  8671. RHS.get()->getType()->isVectorType()) {
  8672. if (LangOpts.ZVector) {
  8673. // The shift operators for the z vector extensions work basically
  8674. // like general shifts, except that neither the LHS nor the RHS is
  8675. // allowed to be a "vector bool".
  8676. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8677. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8678. return InvalidOperands(Loc, LHS, RHS);
  8679. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8680. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8681. return InvalidOperands(Loc, LHS, RHS);
  8682. }
  8683. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8684. }
  8685. // Shifts don't perform usual arithmetic conversions, they just do integer
  8686. // promotions on each operand. C99 6.5.7p3
  8687. // For the LHS, do usual unary conversions, but then reset them away
  8688. // if this is a compound assignment.
  8689. ExprResult OldLHS = LHS;
  8690. LHS = UsualUnaryConversions(LHS.get());
  8691. if (LHS.isInvalid())
  8692. return QualType();
  8693. QualType LHSType = LHS.get()->getType();
  8694. if (IsCompAssign) LHS = OldLHS;
  8695. // The RHS is simpler.
  8696. RHS = UsualUnaryConversions(RHS.get());
  8697. if (RHS.isInvalid())
  8698. return QualType();
  8699. QualType RHSType = RHS.get()->getType();
  8700. // C99 6.5.7p2: Each of the operands shall have integer type.
  8701. if (!LHSType->hasIntegerRepresentation() ||
  8702. !RHSType->hasIntegerRepresentation())
  8703. return InvalidOperands(Loc, LHS, RHS);
  8704. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8705. // hasIntegerRepresentation() above instead of this.
  8706. if (isScopedEnumerationType(LHSType) ||
  8707. isScopedEnumerationType(RHSType)) {
  8708. return InvalidOperands(Loc, LHS, RHS);
  8709. }
  8710. // Sanity-check shift operands
  8711. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8712. // "The type of the result is that of the promoted left operand."
  8713. return LHSType;
  8714. }
  8715. /// If two different enums are compared, raise a warning.
  8716. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8717. Expr *RHS) {
  8718. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8719. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8720. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8721. if (!LHSEnumType)
  8722. return;
  8723. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8724. if (!RHSEnumType)
  8725. return;
  8726. // Ignore anonymous enums.
  8727. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8728. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8729. return;
  8730. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8731. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8732. return;
  8733. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8734. return;
  8735. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8736. << LHSStrippedType << RHSStrippedType
  8737. << LHS->getSourceRange() << RHS->getSourceRange();
  8738. }
  8739. /// Diagnose bad pointer comparisons.
  8740. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8741. ExprResult &LHS, ExprResult &RHS,
  8742. bool IsError) {
  8743. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8744. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8745. << LHS.get()->getType() << RHS.get()->getType()
  8746. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8747. }
  8748. /// Returns false if the pointers are converted to a composite type,
  8749. /// true otherwise.
  8750. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8751. ExprResult &LHS, ExprResult &RHS) {
  8752. // C++ [expr.rel]p2:
  8753. // [...] Pointer conversions (4.10) and qualification
  8754. // conversions (4.4) are performed on pointer operands (or on
  8755. // a pointer operand and a null pointer constant) to bring
  8756. // them to their composite pointer type. [...]
  8757. //
  8758. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8759. // comparisons of pointers.
  8760. QualType LHSType = LHS.get()->getType();
  8761. QualType RHSType = RHS.get()->getType();
  8762. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8763. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8764. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8765. if (T.isNull()) {
  8766. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8767. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8768. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8769. else
  8770. S.InvalidOperands(Loc, LHS, RHS);
  8771. return true;
  8772. }
  8773. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8774. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8775. return false;
  8776. }
  8777. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8778. ExprResult &LHS,
  8779. ExprResult &RHS,
  8780. bool IsError) {
  8781. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8782. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8783. << LHS.get()->getType() << RHS.get()->getType()
  8784. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8785. }
  8786. static bool isObjCObjectLiteral(ExprResult &E) {
  8787. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8788. case Stmt::ObjCArrayLiteralClass:
  8789. case Stmt::ObjCDictionaryLiteralClass:
  8790. case Stmt::ObjCStringLiteralClass:
  8791. case Stmt::ObjCBoxedExprClass:
  8792. return true;
  8793. default:
  8794. // Note that ObjCBoolLiteral is NOT an object literal!
  8795. return false;
  8796. }
  8797. }
  8798. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8799. const ObjCObjectPointerType *Type =
  8800. LHS->getType()->getAs<ObjCObjectPointerType>();
  8801. // If this is not actually an Objective-C object, bail out.
  8802. if (!Type)
  8803. return false;
  8804. // Get the LHS object's interface type.
  8805. QualType InterfaceType = Type->getPointeeType();
  8806. // If the RHS isn't an Objective-C object, bail out.
  8807. if (!RHS->getType()->isObjCObjectPointerType())
  8808. return false;
  8809. // Try to find the -isEqual: method.
  8810. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8811. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8812. InterfaceType,
  8813. /*IsInstance=*/true);
  8814. if (!Method) {
  8815. if (Type->isObjCIdType()) {
  8816. // For 'id', just check the global pool.
  8817. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8818. /*receiverId=*/true);
  8819. } else {
  8820. // Check protocols.
  8821. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8822. /*IsInstance=*/true);
  8823. }
  8824. }
  8825. if (!Method)
  8826. return false;
  8827. QualType T = Method->parameters()[0]->getType();
  8828. if (!T->isObjCObjectPointerType())
  8829. return false;
  8830. QualType R = Method->getReturnType();
  8831. if (!R->isScalarType())
  8832. return false;
  8833. return true;
  8834. }
  8835. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8836. FromE = FromE->IgnoreParenImpCasts();
  8837. switch (FromE->getStmtClass()) {
  8838. default:
  8839. break;
  8840. case Stmt::ObjCStringLiteralClass:
  8841. // "string literal"
  8842. return LK_String;
  8843. case Stmt::ObjCArrayLiteralClass:
  8844. // "array literal"
  8845. return LK_Array;
  8846. case Stmt::ObjCDictionaryLiteralClass:
  8847. // "dictionary literal"
  8848. return LK_Dictionary;
  8849. case Stmt::BlockExprClass:
  8850. return LK_Block;
  8851. case Stmt::ObjCBoxedExprClass: {
  8852. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8853. switch (Inner->getStmtClass()) {
  8854. case Stmt::IntegerLiteralClass:
  8855. case Stmt::FloatingLiteralClass:
  8856. case Stmt::CharacterLiteralClass:
  8857. case Stmt::ObjCBoolLiteralExprClass:
  8858. case Stmt::CXXBoolLiteralExprClass:
  8859. // "numeric literal"
  8860. return LK_Numeric;
  8861. case Stmt::ImplicitCastExprClass: {
  8862. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8863. // Boolean literals can be represented by implicit casts.
  8864. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8865. return LK_Numeric;
  8866. break;
  8867. }
  8868. default:
  8869. break;
  8870. }
  8871. return LK_Boxed;
  8872. }
  8873. }
  8874. return LK_None;
  8875. }
  8876. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8877. ExprResult &LHS, ExprResult &RHS,
  8878. BinaryOperator::Opcode Opc){
  8879. Expr *Literal;
  8880. Expr *Other;
  8881. if (isObjCObjectLiteral(LHS)) {
  8882. Literal = LHS.get();
  8883. Other = RHS.get();
  8884. } else {
  8885. Literal = RHS.get();
  8886. Other = LHS.get();
  8887. }
  8888. // Don't warn on comparisons against nil.
  8889. Other = Other->IgnoreParenCasts();
  8890. if (Other->isNullPointerConstant(S.getASTContext(),
  8891. Expr::NPC_ValueDependentIsNotNull))
  8892. return;
  8893. // This should be kept in sync with warn_objc_literal_comparison.
  8894. // LK_String should always be after the other literals, since it has its own
  8895. // warning flag.
  8896. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8897. assert(LiteralKind != Sema::LK_Block);
  8898. if (LiteralKind == Sema::LK_None) {
  8899. llvm_unreachable("Unknown Objective-C object literal kind");
  8900. }
  8901. if (LiteralKind == Sema::LK_String)
  8902. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8903. << Literal->getSourceRange();
  8904. else
  8905. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8906. << LiteralKind << Literal->getSourceRange();
  8907. if (BinaryOperator::isEqualityOp(Opc) &&
  8908. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8909. SourceLocation Start = LHS.get()->getBeginLoc();
  8910. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
  8911. CharSourceRange OpRange =
  8912. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8913. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8914. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8915. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8916. << FixItHint::CreateInsertion(End, "]");
  8917. }
  8918. }
  8919. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8920. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8921. ExprResult &RHS, SourceLocation Loc,
  8922. BinaryOperatorKind Opc) {
  8923. // Check that left hand side is !something.
  8924. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8925. if (!UO || UO->getOpcode() != UO_LNot) return;
  8926. // Only check if the right hand side is non-bool arithmetic type.
  8927. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8928. // Make sure that the something in !something is not bool.
  8929. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8930. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8931. // Emit warning.
  8932. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8933. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8934. << Loc << IsBitwiseOp;
  8935. // First note suggest !(x < y)
  8936. SourceLocation FirstOpen = SubExpr->getBeginLoc();
  8937. SourceLocation FirstClose = RHS.get()->getEndLoc();
  8938. FirstClose = S.getLocForEndOfToken(FirstClose);
  8939. if (FirstClose.isInvalid())
  8940. FirstOpen = SourceLocation();
  8941. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8942. << IsBitwiseOp
  8943. << FixItHint::CreateInsertion(FirstOpen, "(")
  8944. << FixItHint::CreateInsertion(FirstClose, ")");
  8945. // Second note suggests (!x) < y
  8946. SourceLocation SecondOpen = LHS.get()->getBeginLoc();
  8947. SourceLocation SecondClose = LHS.get()->getEndLoc();
  8948. SecondClose = S.getLocForEndOfToken(SecondClose);
  8949. if (SecondClose.isInvalid())
  8950. SecondOpen = SourceLocation();
  8951. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8952. << FixItHint::CreateInsertion(SecondOpen, "(")
  8953. << FixItHint::CreateInsertion(SecondClose, ")");
  8954. }
  8955. // Get the decl for a simple expression: a reference to a variable,
  8956. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  8957. static ValueDecl *getCompareDecl(Expr *E) {
  8958. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
  8959. return DR->getDecl();
  8960. if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  8961. if (Ivar->isFreeIvar())
  8962. return Ivar->getDecl();
  8963. }
  8964. if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
  8965. if (Mem->isImplicitAccess())
  8966. return Mem->getMemberDecl();
  8967. }
  8968. return nullptr;
  8969. }
  8970. /// Diagnose some forms of syntactically-obvious tautological comparison.
  8971. static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
  8972. Expr *LHS, Expr *RHS,
  8973. BinaryOperatorKind Opc) {
  8974. Expr *LHSStripped = LHS->IgnoreParenImpCasts();
  8975. Expr *RHSStripped = RHS->IgnoreParenImpCasts();
  8976. QualType LHSType = LHS->getType();
  8977. QualType RHSType = RHS->getType();
  8978. if (LHSType->hasFloatingRepresentation() ||
  8979. (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
  8980. LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
  8981. S.inTemplateInstantiation())
  8982. return;
  8983. // Comparisons between two array types are ill-formed for operator<=>, so
  8984. // we shouldn't emit any additional warnings about it.
  8985. if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
  8986. return;
  8987. // For non-floating point types, check for self-comparisons of the form
  8988. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8989. // often indicate logic errors in the program.
  8990. //
  8991. // NOTE: Don't warn about comparison expressions resulting from macro
  8992. // expansion. Also don't warn about comparisons which are only self
  8993. // comparisons within a template instantiation. The warnings should catch
  8994. // obvious cases in the definition of the template anyways. The idea is to
  8995. // warn when the typed comparison operator will always evaluate to the same
  8996. // result.
  8997. ValueDecl *DL = getCompareDecl(LHSStripped);
  8998. ValueDecl *DR = getCompareDecl(RHSStripped);
  8999. // Used for indexing into %select in warn_comparison_always
  9000. enum {
  9001. AlwaysConstant,
  9002. AlwaysTrue,
  9003. AlwaysFalse,
  9004. AlwaysEqual, // std::strong_ordering::equal from operator<=>
  9005. };
  9006. if (DL && DR && declaresSameEntity(DL, DR)) {
  9007. unsigned Result;
  9008. switch (Opc) {
  9009. case BO_EQ: case BO_LE: case BO_GE:
  9010. Result = AlwaysTrue;
  9011. break;
  9012. case BO_NE: case BO_LT: case BO_GT:
  9013. Result = AlwaysFalse;
  9014. break;
  9015. case BO_Cmp:
  9016. Result = AlwaysEqual;
  9017. break;
  9018. default:
  9019. Result = AlwaysConstant;
  9020. break;
  9021. }
  9022. S.DiagRuntimeBehavior(Loc, nullptr,
  9023. S.PDiag(diag::warn_comparison_always)
  9024. << 0 /*self-comparison*/
  9025. << Result);
  9026. } else if (DL && DR &&
  9027. DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
  9028. !DL->isWeak() && !DR->isWeak()) {
  9029. // What is it always going to evaluate to?
  9030. unsigned Result;
  9031. switch(Opc) {
  9032. case BO_EQ: // e.g. array1 == array2
  9033. Result = AlwaysFalse;
  9034. break;
  9035. case BO_NE: // e.g. array1 != array2
  9036. Result = AlwaysTrue;
  9037. break;
  9038. default: // e.g. array1 <= array2
  9039. // The best we can say is 'a constant'
  9040. Result = AlwaysConstant;
  9041. break;
  9042. }
  9043. S.DiagRuntimeBehavior(Loc, nullptr,
  9044. S.PDiag(diag::warn_comparison_always)
  9045. << 1 /*array comparison*/
  9046. << Result);
  9047. }
  9048. if (isa<CastExpr>(LHSStripped))
  9049. LHSStripped = LHSStripped->IgnoreParenCasts();
  9050. if (isa<CastExpr>(RHSStripped))
  9051. RHSStripped = RHSStripped->IgnoreParenCasts();
  9052. // Warn about comparisons against a string constant (unless the other
  9053. // operand is null); the user probably wants strcmp.
  9054. Expr *LiteralString = nullptr;
  9055. Expr *LiteralStringStripped = nullptr;
  9056. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  9057. !RHSStripped->isNullPointerConstant(S.Context,
  9058. Expr::NPC_ValueDependentIsNull)) {
  9059. LiteralString = LHS;
  9060. LiteralStringStripped = LHSStripped;
  9061. } else if ((isa<StringLiteral>(RHSStripped) ||
  9062. isa<ObjCEncodeExpr>(RHSStripped)) &&
  9063. !LHSStripped->isNullPointerConstant(S.Context,
  9064. Expr::NPC_ValueDependentIsNull)) {
  9065. LiteralString = RHS;
  9066. LiteralStringStripped = RHSStripped;
  9067. }
  9068. if (LiteralString) {
  9069. S.DiagRuntimeBehavior(Loc, nullptr,
  9070. S.PDiag(diag::warn_stringcompare)
  9071. << isa<ObjCEncodeExpr>(LiteralStringStripped)
  9072. << LiteralString->getSourceRange());
  9073. }
  9074. }
  9075. static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
  9076. switch (CK) {
  9077. default: {
  9078. #ifndef NDEBUG
  9079. llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
  9080. << "\n";
  9081. #endif
  9082. llvm_unreachable("unhandled cast kind");
  9083. }
  9084. case CK_UserDefinedConversion:
  9085. return ICK_Identity;
  9086. case CK_LValueToRValue:
  9087. return ICK_Lvalue_To_Rvalue;
  9088. case CK_ArrayToPointerDecay:
  9089. return ICK_Array_To_Pointer;
  9090. case CK_FunctionToPointerDecay:
  9091. return ICK_Function_To_Pointer;
  9092. case CK_IntegralCast:
  9093. return ICK_Integral_Conversion;
  9094. case CK_FloatingCast:
  9095. return ICK_Floating_Conversion;
  9096. case CK_IntegralToFloating:
  9097. case CK_FloatingToIntegral:
  9098. return ICK_Floating_Integral;
  9099. case CK_IntegralComplexCast:
  9100. case CK_FloatingComplexCast:
  9101. case CK_FloatingComplexToIntegralComplex:
  9102. case CK_IntegralComplexToFloatingComplex:
  9103. return ICK_Complex_Conversion;
  9104. case CK_FloatingComplexToReal:
  9105. case CK_FloatingRealToComplex:
  9106. case CK_IntegralComplexToReal:
  9107. case CK_IntegralRealToComplex:
  9108. return ICK_Complex_Real;
  9109. }
  9110. }
  9111. static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
  9112. QualType FromType,
  9113. SourceLocation Loc) {
  9114. // Check for a narrowing implicit conversion.
  9115. StandardConversionSequence SCS;
  9116. SCS.setAsIdentityConversion();
  9117. SCS.setToType(0, FromType);
  9118. SCS.setToType(1, ToType);
  9119. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  9120. SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
  9121. APValue PreNarrowingValue;
  9122. QualType PreNarrowingType;
  9123. switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
  9124. PreNarrowingType,
  9125. /*IgnoreFloatToIntegralConversion*/ true)) {
  9126. case NK_Dependent_Narrowing:
  9127. // Implicit conversion to a narrower type, but the expression is
  9128. // value-dependent so we can't tell whether it's actually narrowing.
  9129. case NK_Not_Narrowing:
  9130. return false;
  9131. case NK_Constant_Narrowing:
  9132. // Implicit conversion to a narrower type, and the value is not a constant
  9133. // expression.
  9134. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9135. << /*Constant*/ 1
  9136. << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
  9137. return true;
  9138. case NK_Variable_Narrowing:
  9139. // Implicit conversion to a narrower type, and the value is not a constant
  9140. // expression.
  9141. case NK_Type_Narrowing:
  9142. S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
  9143. << /*Constant*/ 0 << FromType << ToType;
  9144. // TODO: It's not a constant expression, but what if the user intended it
  9145. // to be? Can we produce notes to help them figure out why it isn't?
  9146. return true;
  9147. }
  9148. llvm_unreachable("unhandled case in switch");
  9149. }
  9150. static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
  9151. ExprResult &LHS,
  9152. ExprResult &RHS,
  9153. SourceLocation Loc) {
  9154. using CCT = ComparisonCategoryType;
  9155. QualType LHSType = LHS.get()->getType();
  9156. QualType RHSType = RHS.get()->getType();
  9157. // Dig out the original argument type and expression before implicit casts
  9158. // were applied. These are the types/expressions we need to check the
  9159. // [expr.spaceship] requirements against.
  9160. ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
  9161. ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
  9162. QualType LHSStrippedType = LHSStripped.get()->getType();
  9163. QualType RHSStrippedType = RHSStripped.get()->getType();
  9164. // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
  9165. // other is not, the program is ill-formed.
  9166. if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
  9167. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9168. return QualType();
  9169. }
  9170. int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
  9171. RHSStrippedType->isEnumeralType();
  9172. if (NumEnumArgs == 1) {
  9173. bool LHSIsEnum = LHSStrippedType->isEnumeralType();
  9174. QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
  9175. if (OtherTy->hasFloatingRepresentation()) {
  9176. S.InvalidOperands(Loc, LHSStripped, RHSStripped);
  9177. return QualType();
  9178. }
  9179. }
  9180. if (NumEnumArgs == 2) {
  9181. // C++2a [expr.spaceship]p5: If both operands have the same enumeration
  9182. // type E, the operator yields the result of converting the operands
  9183. // to the underlying type of E and applying <=> to the converted operands.
  9184. if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
  9185. S.InvalidOperands(Loc, LHS, RHS);
  9186. return QualType();
  9187. }
  9188. QualType IntType =
  9189. LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
  9190. assert(IntType->isArithmeticType());
  9191. // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
  9192. // promote the boolean type, and all other promotable integer types, to
  9193. // avoid this.
  9194. if (IntType->isPromotableIntegerType())
  9195. IntType = S.Context.getPromotedIntegerType(IntType);
  9196. LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
  9197. RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
  9198. LHSType = RHSType = IntType;
  9199. }
  9200. // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
  9201. // usual arithmetic conversions are applied to the operands.
  9202. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9203. if (LHS.isInvalid() || RHS.isInvalid())
  9204. return QualType();
  9205. if (Type.isNull())
  9206. return S.InvalidOperands(Loc, LHS, RHS);
  9207. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9208. bool HasNarrowing = checkThreeWayNarrowingConversion(
  9209. S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
  9210. HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
  9211. RHS.get()->getBeginLoc());
  9212. if (HasNarrowing)
  9213. return QualType();
  9214. assert(!Type.isNull() && "composite type for <=> has not been set");
  9215. auto TypeKind = [&]() {
  9216. if (const ComplexType *CT = Type->getAs<ComplexType>()) {
  9217. if (CT->getElementType()->hasFloatingRepresentation())
  9218. return CCT::WeakEquality;
  9219. return CCT::StrongEquality;
  9220. }
  9221. if (Type->isIntegralOrEnumerationType())
  9222. return CCT::StrongOrdering;
  9223. if (Type->hasFloatingRepresentation())
  9224. return CCT::PartialOrdering;
  9225. llvm_unreachable("other types are unimplemented");
  9226. }();
  9227. return S.CheckComparisonCategoryType(TypeKind, Loc);
  9228. }
  9229. static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
  9230. ExprResult &RHS,
  9231. SourceLocation Loc,
  9232. BinaryOperatorKind Opc) {
  9233. if (Opc == BO_Cmp)
  9234. return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
  9235. // C99 6.5.8p3 / C99 6.5.9p4
  9236. QualType Type = S.UsualArithmeticConversions(LHS, RHS);
  9237. if (LHS.isInvalid() || RHS.isInvalid())
  9238. return QualType();
  9239. if (Type.isNull())
  9240. return S.InvalidOperands(Loc, LHS, RHS);
  9241. assert(Type->isArithmeticType() || Type->isEnumeralType());
  9242. checkEnumComparison(S, Loc, LHS.get(), RHS.get());
  9243. if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
  9244. return S.InvalidOperands(Loc, LHS, RHS);
  9245. // Check for comparisons of floating point operands using != and ==.
  9246. if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
  9247. S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9248. // The result of comparisons is 'bool' in C++, 'int' in C.
  9249. return S.Context.getLogicalOperationType();
  9250. }
  9251. void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
  9252. if (!NullE.get()->getType()->isAnyPointerType())
  9253. return;
  9254. int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
  9255. if (!E.get()->getType()->isAnyPointerType() &&
  9256. E.get()->isNullPointerConstant(Context,
  9257. Expr::NPC_ValueDependentIsNotNull) ==
  9258. Expr::NPCK_ZeroExpression) {
  9259. if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
  9260. if (CL->getValue() == 0)
  9261. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9262. << NullValue
  9263. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9264. NullValue ? "NULL" : "(void *)0");
  9265. } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
  9266. TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
  9267. QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
  9268. if (T == Context.CharTy)
  9269. Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
  9270. << NullValue
  9271. << FixItHint::CreateReplacement(E.get()->getExprLoc(),
  9272. NullValue ? "NULL" : "(void *)0");
  9273. }
  9274. }
  9275. }
  9276. // C99 6.5.8, C++ [expr.rel]
  9277. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9278. SourceLocation Loc,
  9279. BinaryOperatorKind Opc) {
  9280. bool IsRelational = BinaryOperator::isRelationalOp(Opc);
  9281. bool IsThreeWay = Opc == BO_Cmp;
  9282. auto IsAnyPointerType = [](ExprResult E) {
  9283. QualType Ty = E.get()->getType();
  9284. return Ty->isPointerType() || Ty->isMemberPointerType();
  9285. };
  9286. // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
  9287. // type, array-to-pointer, ..., conversions are performed on both operands to
  9288. // bring them to their composite type.
  9289. // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
  9290. // any type-related checks.
  9291. if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
  9292. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  9293. if (LHS.isInvalid())
  9294. return QualType();
  9295. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  9296. if (RHS.isInvalid())
  9297. return QualType();
  9298. } else {
  9299. LHS = DefaultLvalueConversion(LHS.get());
  9300. if (LHS.isInvalid())
  9301. return QualType();
  9302. RHS = DefaultLvalueConversion(RHS.get());
  9303. if (RHS.isInvalid())
  9304. return QualType();
  9305. }
  9306. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
  9307. if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
  9308. CheckPtrComparisonWithNullChar(LHS, RHS);
  9309. CheckPtrComparisonWithNullChar(RHS, LHS);
  9310. }
  9311. // Handle vector comparisons separately.
  9312. if (LHS.get()->getType()->isVectorType() ||
  9313. RHS.get()->getType()->isVectorType())
  9314. return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
  9315. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9316. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9317. QualType LHSType = LHS.get()->getType();
  9318. QualType RHSType = RHS.get()->getType();
  9319. if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
  9320. (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
  9321. return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
  9322. const Expr::NullPointerConstantKind LHSNullKind =
  9323. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9324. const Expr::NullPointerConstantKind RHSNullKind =
  9325. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  9326. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  9327. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  9328. auto computeResultTy = [&]() {
  9329. if (Opc != BO_Cmp)
  9330. return Context.getLogicalOperationType();
  9331. assert(getLangOpts().CPlusPlus);
  9332. assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
  9333. QualType CompositeTy = LHS.get()->getType();
  9334. assert(!CompositeTy->isReferenceType());
  9335. auto buildResultTy = [&](ComparisonCategoryType Kind) {
  9336. return CheckComparisonCategoryType(Kind, Loc);
  9337. };
  9338. // C++2a [expr.spaceship]p7: If the composite pointer type is a function
  9339. // pointer type, a pointer-to-member type, or std::nullptr_t, the
  9340. // result is of type std::strong_equality
  9341. if (CompositeTy->isFunctionPointerType() ||
  9342. CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
  9343. // FIXME: consider making the function pointer case produce
  9344. // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
  9345. // and direction polls
  9346. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9347. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  9348. // pointer type, p <=> q is of type std::strong_ordering.
  9349. if (CompositeTy->isPointerType()) {
  9350. // P0946R0: Comparisons between a null pointer constant and an object
  9351. // pointer result in std::strong_equality
  9352. if (LHSIsNull != RHSIsNull)
  9353. return buildResultTy(ComparisonCategoryType::StrongEquality);
  9354. return buildResultTy(ComparisonCategoryType::StrongOrdering);
  9355. }
  9356. // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
  9357. // TODO: Extend support for operator<=> to ObjC types.
  9358. return InvalidOperands(Loc, LHS, RHS);
  9359. };
  9360. if (!IsRelational && LHSIsNull != RHSIsNull) {
  9361. bool IsEquality = Opc == BO_EQ;
  9362. if (RHSIsNull)
  9363. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  9364. RHS.get()->getSourceRange());
  9365. else
  9366. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  9367. LHS.get()->getSourceRange());
  9368. }
  9369. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  9370. (RHSType->isIntegerType() && !RHSIsNull)) {
  9371. // Skip normal pointer conversion checks in this case; we have better
  9372. // diagnostics for this below.
  9373. } else if (getLangOpts().CPlusPlus) {
  9374. // Equality comparison of a function pointer to a void pointer is invalid,
  9375. // but we allow it as an extension.
  9376. // FIXME: If we really want to allow this, should it be part of composite
  9377. // pointer type computation so it works in conditionals too?
  9378. if (!IsRelational &&
  9379. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  9380. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  9381. // This is a gcc extension compatibility comparison.
  9382. // In a SFINAE context, we treat this as a hard error to maintain
  9383. // conformance with the C++ standard.
  9384. diagnoseFunctionPointerToVoidComparison(
  9385. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  9386. if (isSFINAEContext())
  9387. return QualType();
  9388. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9389. return computeResultTy();
  9390. }
  9391. // C++ [expr.eq]p2:
  9392. // If at least one operand is a pointer [...] bring them to their
  9393. // composite pointer type.
  9394. // C++ [expr.spaceship]p6
  9395. // If at least one of the operands is of pointer type, [...] bring them
  9396. // to their composite pointer type.
  9397. // C++ [expr.rel]p2:
  9398. // If both operands are pointers, [...] bring them to their composite
  9399. // pointer type.
  9400. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  9401. (IsRelational ? 2 : 1) &&
  9402. (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
  9403. RHSType->isObjCObjectPointerType()))) {
  9404. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9405. return QualType();
  9406. return computeResultTy();
  9407. }
  9408. } else if (LHSType->isPointerType() &&
  9409. RHSType->isPointerType()) { // C99 6.5.8p2
  9410. // All of the following pointer-related warnings are GCC extensions, except
  9411. // when handling null pointer constants.
  9412. QualType LCanPointeeTy =
  9413. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9414. QualType RCanPointeeTy =
  9415. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  9416. // C99 6.5.9p2 and C99 6.5.8p2
  9417. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  9418. RCanPointeeTy.getUnqualifiedType())) {
  9419. // Valid unless a relational comparison of function pointers
  9420. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  9421. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  9422. << LHSType << RHSType << LHS.get()->getSourceRange()
  9423. << RHS.get()->getSourceRange();
  9424. }
  9425. } else if (!IsRelational &&
  9426. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  9427. // Valid unless comparison between non-null pointer and function pointer
  9428. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  9429. && !LHSIsNull && !RHSIsNull)
  9430. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  9431. /*isError*/false);
  9432. } else {
  9433. // Invalid
  9434. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  9435. }
  9436. if (LCanPointeeTy != RCanPointeeTy) {
  9437. // Treat NULL constant as a special case in OpenCL.
  9438. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  9439. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  9440. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  9441. Diag(Loc,
  9442. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  9443. << LHSType << RHSType << 0 /* comparison */
  9444. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  9445. }
  9446. }
  9447. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  9448. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  9449. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  9450. : CK_BitCast;
  9451. if (LHSIsNull && !RHSIsNull)
  9452. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  9453. else
  9454. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  9455. }
  9456. return computeResultTy();
  9457. }
  9458. if (getLangOpts().CPlusPlus) {
  9459. // C++ [expr.eq]p4:
  9460. // Two operands of type std::nullptr_t or one operand of type
  9461. // std::nullptr_t and the other a null pointer constant compare equal.
  9462. if (!IsRelational && LHSIsNull && RHSIsNull) {
  9463. if (LHSType->isNullPtrType()) {
  9464. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9465. return computeResultTy();
  9466. }
  9467. if (RHSType->isNullPtrType()) {
  9468. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9469. return computeResultTy();
  9470. }
  9471. }
  9472. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  9473. // These aren't covered by the composite pointer type rules.
  9474. if (!IsRelational && RHSType->isNullPtrType() &&
  9475. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  9476. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9477. return computeResultTy();
  9478. }
  9479. if (!IsRelational && LHSType->isNullPtrType() &&
  9480. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  9481. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9482. return computeResultTy();
  9483. }
  9484. if (IsRelational &&
  9485. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  9486. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  9487. // HACK: Relational comparison of nullptr_t against a pointer type is
  9488. // invalid per DR583, but we allow it within std::less<> and friends,
  9489. // since otherwise common uses of it break.
  9490. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  9491. // friends to have std::nullptr_t overload candidates.
  9492. DeclContext *DC = CurContext;
  9493. if (isa<FunctionDecl>(DC))
  9494. DC = DC->getParent();
  9495. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  9496. if (CTSD->isInStdNamespace() &&
  9497. llvm::StringSwitch<bool>(CTSD->getName())
  9498. .Cases("less", "less_equal", "greater", "greater_equal", true)
  9499. .Default(false)) {
  9500. if (RHSType->isNullPtrType())
  9501. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9502. else
  9503. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9504. return computeResultTy();
  9505. }
  9506. }
  9507. }
  9508. // C++ [expr.eq]p2:
  9509. // If at least one operand is a pointer to member, [...] bring them to
  9510. // their composite pointer type.
  9511. if (!IsRelational &&
  9512. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  9513. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  9514. return QualType();
  9515. else
  9516. return computeResultTy();
  9517. }
  9518. }
  9519. // Handle block pointer types.
  9520. if (!IsRelational && LHSType->isBlockPointerType() &&
  9521. RHSType->isBlockPointerType()) {
  9522. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  9523. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  9524. if (!LHSIsNull && !RHSIsNull &&
  9525. !Context.typesAreCompatible(lpointee, rpointee)) {
  9526. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9527. << LHSType << RHSType << LHS.get()->getSourceRange()
  9528. << RHS.get()->getSourceRange();
  9529. }
  9530. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9531. return computeResultTy();
  9532. }
  9533. // Allow block pointers to be compared with null pointer constants.
  9534. if (!IsRelational
  9535. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  9536. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  9537. if (!LHSIsNull && !RHSIsNull) {
  9538. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  9539. ->getPointeeType()->isVoidType())
  9540. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  9541. ->getPointeeType()->isVoidType())))
  9542. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  9543. << LHSType << RHSType << LHS.get()->getSourceRange()
  9544. << RHS.get()->getSourceRange();
  9545. }
  9546. if (LHSIsNull && !RHSIsNull)
  9547. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9548. RHSType->isPointerType() ? CK_BitCast
  9549. : CK_AnyPointerToBlockPointerCast);
  9550. else
  9551. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9552. LHSType->isPointerType() ? CK_BitCast
  9553. : CK_AnyPointerToBlockPointerCast);
  9554. return computeResultTy();
  9555. }
  9556. if (LHSType->isObjCObjectPointerType() ||
  9557. RHSType->isObjCObjectPointerType()) {
  9558. const PointerType *LPT = LHSType->getAs<PointerType>();
  9559. const PointerType *RPT = RHSType->getAs<PointerType>();
  9560. if (LPT || RPT) {
  9561. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  9562. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  9563. if (!LPtrToVoid && !RPtrToVoid &&
  9564. !Context.typesAreCompatible(LHSType, RHSType)) {
  9565. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9566. /*isError*/false);
  9567. }
  9568. if (LHSIsNull && !RHSIsNull) {
  9569. Expr *E = LHS.get();
  9570. if (getLangOpts().ObjCAutoRefCount)
  9571. CheckObjCConversion(SourceRange(), RHSType, E,
  9572. CCK_ImplicitConversion);
  9573. LHS = ImpCastExprToType(E, RHSType,
  9574. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9575. }
  9576. else {
  9577. Expr *E = RHS.get();
  9578. if (getLangOpts().ObjCAutoRefCount)
  9579. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  9580. /*Diagnose=*/true,
  9581. /*DiagnoseCFAudited=*/false, Opc);
  9582. RHS = ImpCastExprToType(E, LHSType,
  9583. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  9584. }
  9585. return computeResultTy();
  9586. }
  9587. if (LHSType->isObjCObjectPointerType() &&
  9588. RHSType->isObjCObjectPointerType()) {
  9589. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  9590. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  9591. /*isError*/false);
  9592. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  9593. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  9594. if (LHSIsNull && !RHSIsNull)
  9595. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  9596. else
  9597. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  9598. return computeResultTy();
  9599. }
  9600. if (!IsRelational && LHSType->isBlockPointerType() &&
  9601. RHSType->isBlockCompatibleObjCPointerType(Context)) {
  9602. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9603. CK_BlockPointerToObjCPointerCast);
  9604. return computeResultTy();
  9605. } else if (!IsRelational &&
  9606. LHSType->isBlockCompatibleObjCPointerType(Context) &&
  9607. RHSType->isBlockPointerType()) {
  9608. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9609. CK_BlockPointerToObjCPointerCast);
  9610. return computeResultTy();
  9611. }
  9612. }
  9613. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  9614. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  9615. unsigned DiagID = 0;
  9616. bool isError = false;
  9617. if (LangOpts.DebuggerSupport) {
  9618. // Under a debugger, allow the comparison of pointers to integers,
  9619. // since users tend to want to compare addresses.
  9620. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  9621. (RHSIsNull && RHSType->isIntegerType())) {
  9622. if (IsRelational) {
  9623. isError = getLangOpts().CPlusPlus;
  9624. DiagID =
  9625. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  9626. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  9627. }
  9628. } else if (getLangOpts().CPlusPlus) {
  9629. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  9630. isError = true;
  9631. } else if (IsRelational)
  9632. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  9633. else
  9634. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  9635. if (DiagID) {
  9636. Diag(Loc, DiagID)
  9637. << LHSType << RHSType << LHS.get()->getSourceRange()
  9638. << RHS.get()->getSourceRange();
  9639. if (isError)
  9640. return QualType();
  9641. }
  9642. if (LHSType->isIntegerType())
  9643. LHS = ImpCastExprToType(LHS.get(), RHSType,
  9644. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9645. else
  9646. RHS = ImpCastExprToType(RHS.get(), LHSType,
  9647. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  9648. return computeResultTy();
  9649. }
  9650. // Handle block pointers.
  9651. if (!IsRelational && RHSIsNull
  9652. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  9653. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9654. return computeResultTy();
  9655. }
  9656. if (!IsRelational && LHSIsNull
  9657. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  9658. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9659. return computeResultTy();
  9660. }
  9661. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  9662. if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
  9663. return computeResultTy();
  9664. }
  9665. if (LHSType->isQueueT() && RHSType->isQueueT()) {
  9666. return computeResultTy();
  9667. }
  9668. if (LHSIsNull && RHSType->isQueueT()) {
  9669. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  9670. return computeResultTy();
  9671. }
  9672. if (LHSType->isQueueT() && RHSIsNull) {
  9673. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  9674. return computeResultTy();
  9675. }
  9676. }
  9677. return InvalidOperands(Loc, LHS, RHS);
  9678. }
  9679. // Return a signed ext_vector_type that is of identical size and number of
  9680. // elements. For floating point vectors, return an integer type of identical
  9681. // size and number of elements. In the non ext_vector_type case, search from
  9682. // the largest type to the smallest type to avoid cases where long long == long,
  9683. // where long gets picked over long long.
  9684. QualType Sema::GetSignedVectorType(QualType V) {
  9685. const VectorType *VTy = V->getAs<VectorType>();
  9686. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  9687. if (isa<ExtVectorType>(VTy)) {
  9688. if (TypeSize == Context.getTypeSize(Context.CharTy))
  9689. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  9690. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9691. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  9692. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9693. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  9694. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9695. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  9696. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  9697. "Unhandled vector element size in vector compare");
  9698. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  9699. }
  9700. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  9701. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  9702. VectorType::GenericVector);
  9703. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  9704. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  9705. VectorType::GenericVector);
  9706. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  9707. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  9708. VectorType::GenericVector);
  9709. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  9710. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  9711. VectorType::GenericVector);
  9712. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  9713. "Unhandled vector element size in vector compare");
  9714. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  9715. VectorType::GenericVector);
  9716. }
  9717. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  9718. /// operates on extended vector types. Instead of producing an IntTy result,
  9719. /// like a scalar comparison, a vector comparison produces a vector of integer
  9720. /// types.
  9721. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  9722. SourceLocation Loc,
  9723. BinaryOperatorKind Opc) {
  9724. // Check to make sure we're operating on vectors of the same type and width,
  9725. // Allowing one side to be a scalar of element type.
  9726. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  9727. /*AllowBothBool*/true,
  9728. /*AllowBoolConversions*/getLangOpts().ZVector);
  9729. if (vType.isNull())
  9730. return vType;
  9731. QualType LHSType = LHS.get()->getType();
  9732. // If AltiVec, the comparison results in a numeric type, i.e.
  9733. // bool for C++, int for C
  9734. if (getLangOpts().AltiVec &&
  9735. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  9736. return Context.getLogicalOperationType();
  9737. // For non-floating point types, check for self-comparisons of the form
  9738. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  9739. // often indicate logic errors in the program.
  9740. diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
  9741. // Check for comparisons of floating point operands using != and ==.
  9742. if (BinaryOperator::isEqualityOp(Opc) &&
  9743. LHSType->hasFloatingRepresentation()) {
  9744. assert(RHS.get()->getType()->hasFloatingRepresentation());
  9745. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  9746. }
  9747. // Return a signed type for the vector.
  9748. return GetSignedVectorType(vType);
  9749. }
  9750. static void diagnoseXorMisusedAsPow(Sema &S, ExprResult &LHS, ExprResult &RHS,
  9751. SourceLocation Loc) {
  9752. // Do not diagnose macros.
  9753. if (Loc.isMacroID())
  9754. return;
  9755. bool Negative = false;
  9756. const auto *LHSInt = dyn_cast<IntegerLiteral>(LHS.get());
  9757. const auto *RHSInt = dyn_cast<IntegerLiteral>(RHS.get());
  9758. if (!LHSInt)
  9759. return;
  9760. if (!RHSInt) {
  9761. // Check negative literals.
  9762. if (const auto *UO = dyn_cast<UnaryOperator>(RHS.get())) {
  9763. if (UO->getOpcode() != UO_Minus)
  9764. return;
  9765. RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
  9766. if (!RHSInt)
  9767. return;
  9768. Negative = true;
  9769. } else {
  9770. return;
  9771. }
  9772. }
  9773. if (LHSInt->getValue().getBitWidth() != RHSInt->getValue().getBitWidth())
  9774. return;
  9775. CharSourceRange ExprRange = CharSourceRange::getCharRange(
  9776. LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
  9777. llvm::StringRef ExprStr =
  9778. Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
  9779. CharSourceRange XorRange =
  9780. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  9781. llvm::StringRef XorStr =
  9782. Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
  9783. // Do not diagnose if xor keyword/macro is used.
  9784. if (XorStr == "xor")
  9785. return;
  9786. const llvm::APInt &LeftSideValue = LHSInt->getValue();
  9787. const llvm::APInt &RightSideValue = RHSInt->getValue();
  9788. const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
  9789. std::string LHSStr = Lexer::getSourceText(
  9790. CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
  9791. S.getSourceManager(), S.getLangOpts());
  9792. std::string RHSStr = Lexer::getSourceText(
  9793. CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
  9794. S.getSourceManager(), S.getLangOpts());
  9795. int64_t RightSideIntValue = RightSideValue.getSExtValue();
  9796. if (Negative) {
  9797. RightSideIntValue = -RightSideIntValue;
  9798. RHSStr = "-" + RHSStr;
  9799. }
  9800. StringRef LHSStrRef = LHSStr;
  9801. StringRef RHSStrRef = RHSStr;
  9802. // Do not diagnose binary, hexadecimal, octal literals.
  9803. if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
  9804. RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
  9805. LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
  9806. RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
  9807. (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
  9808. (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")))
  9809. return;
  9810. if (LeftSideValue == 2 && RightSideIntValue >= 0) {
  9811. std::string SuggestedExpr = "1 << " + RHSStr;
  9812. bool Overflow = false;
  9813. llvm::APInt One = (LeftSideValue - 1);
  9814. llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
  9815. if (Overflow) {
  9816. if (RightSideIntValue < 64)
  9817. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9818. << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
  9819. << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
  9820. else
  9821. // TODO: 2 ^ 64 - 1
  9822. return;
  9823. } else {
  9824. S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
  9825. << ExprStr << XorValue.toString(10, true) << SuggestedExpr
  9826. << PowValue.toString(10, true)
  9827. << FixItHint::CreateReplacement(
  9828. ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
  9829. }
  9830. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr);
  9831. } else if (LeftSideValue == 10) {
  9832. std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
  9833. S.Diag(Loc, diag::warn_xor_used_as_pow_base)
  9834. << ExprStr << XorValue.toString(10, true) << SuggestedValue
  9835. << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
  9836. S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr);
  9837. }
  9838. }
  9839. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9840. SourceLocation Loc) {
  9841. // Ensure that either both operands are of the same vector type, or
  9842. // one operand is of a vector type and the other is of its element type.
  9843. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  9844. /*AllowBothBool*/true,
  9845. /*AllowBoolConversions*/false);
  9846. if (vType.isNull())
  9847. return InvalidOperands(Loc, LHS, RHS);
  9848. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  9849. !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
  9850. return InvalidOperands(Loc, LHS, RHS);
  9851. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  9852. // usage of the logical operators && and || with vectors in C. This
  9853. // check could be notionally dropped.
  9854. if (!getLangOpts().CPlusPlus &&
  9855. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  9856. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  9857. return GetSignedVectorType(LHS.get()->getType());
  9858. }
  9859. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  9860. SourceLocation Loc,
  9861. BinaryOperatorKind Opc) {
  9862. checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
  9863. bool IsCompAssign =
  9864. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  9865. if (LHS.get()->getType()->isVectorType() ||
  9866. RHS.get()->getType()->isVectorType()) {
  9867. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  9868. RHS.get()->getType()->hasIntegerRepresentation())
  9869. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  9870. /*AllowBothBool*/true,
  9871. /*AllowBoolConversions*/getLangOpts().ZVector);
  9872. return InvalidOperands(Loc, LHS, RHS);
  9873. }
  9874. if (Opc == BO_And)
  9875. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  9876. if (Opc == BO_Xor)
  9877. diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
  9878. ExprResult LHSResult = LHS, RHSResult = RHS;
  9879. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  9880. IsCompAssign);
  9881. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  9882. return QualType();
  9883. LHS = LHSResult.get();
  9884. RHS = RHSResult.get();
  9885. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  9886. return compType;
  9887. return InvalidOperands(Loc, LHS, RHS);
  9888. }
  9889. // C99 6.5.[13,14]
  9890. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  9891. SourceLocation Loc,
  9892. BinaryOperatorKind Opc) {
  9893. // Check vector operands differently.
  9894. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  9895. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  9896. // Diagnose cases where the user write a logical and/or but probably meant a
  9897. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  9898. // is a constant.
  9899. if (LHS.get()->getType()->isIntegerType() &&
  9900. !LHS.get()->getType()->isBooleanType() &&
  9901. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  9902. // Don't warn in macros or template instantiations.
  9903. !Loc.isMacroID() && !inTemplateInstantiation()) {
  9904. // If the RHS can be constant folded, and if it constant folds to something
  9905. // that isn't 0 or 1 (which indicate a potential logical operation that
  9906. // happened to fold to true/false) then warn.
  9907. // Parens on the RHS are ignored.
  9908. Expr::EvalResult EVResult;
  9909. if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
  9910. llvm::APSInt Result = EVResult.Val.getInt();
  9911. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  9912. !RHS.get()->getExprLoc().isMacroID()) ||
  9913. (Result != 0 && Result != 1)) {
  9914. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  9915. << RHS.get()->getSourceRange()
  9916. << (Opc == BO_LAnd ? "&&" : "||");
  9917. // Suggest replacing the logical operator with the bitwise version
  9918. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  9919. << (Opc == BO_LAnd ? "&" : "|")
  9920. << FixItHint::CreateReplacement(SourceRange(
  9921. Loc, getLocForEndOfToken(Loc)),
  9922. Opc == BO_LAnd ? "&" : "|");
  9923. if (Opc == BO_LAnd)
  9924. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  9925. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  9926. << FixItHint::CreateRemoval(
  9927. SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
  9928. RHS.get()->getEndLoc()));
  9929. }
  9930. }
  9931. }
  9932. if (!Context.getLangOpts().CPlusPlus) {
  9933. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9934. // not operate on the built-in scalar and vector float types.
  9935. if (Context.getLangOpts().OpenCL &&
  9936. Context.getLangOpts().OpenCLVersion < 120) {
  9937. if (LHS.get()->getType()->isFloatingType() ||
  9938. RHS.get()->getType()->isFloatingType())
  9939. return InvalidOperands(Loc, LHS, RHS);
  9940. }
  9941. LHS = UsualUnaryConversions(LHS.get());
  9942. if (LHS.isInvalid())
  9943. return QualType();
  9944. RHS = UsualUnaryConversions(RHS.get());
  9945. if (RHS.isInvalid())
  9946. return QualType();
  9947. if (!LHS.get()->getType()->isScalarType() ||
  9948. !RHS.get()->getType()->isScalarType())
  9949. return InvalidOperands(Loc, LHS, RHS);
  9950. return Context.IntTy;
  9951. }
  9952. // The following is safe because we only use this method for
  9953. // non-overloadable operands.
  9954. // C++ [expr.log.and]p1
  9955. // C++ [expr.log.or]p1
  9956. // The operands are both contextually converted to type bool.
  9957. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  9958. if (LHSRes.isInvalid())
  9959. return InvalidOperands(Loc, LHS, RHS);
  9960. LHS = LHSRes;
  9961. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  9962. if (RHSRes.isInvalid())
  9963. return InvalidOperands(Loc, LHS, RHS);
  9964. RHS = RHSRes;
  9965. // C++ [expr.log.and]p2
  9966. // C++ [expr.log.or]p2
  9967. // The result is a bool.
  9968. return Context.BoolTy;
  9969. }
  9970. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  9971. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9972. if (!ME) return false;
  9973. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  9974. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  9975. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  9976. if (!Base) return false;
  9977. return Base->getMethodDecl() != nullptr;
  9978. }
  9979. /// Is the given expression (which must be 'const') a reference to a
  9980. /// variable which was originally non-const, but which has become
  9981. /// 'const' due to being captured within a block?
  9982. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  9983. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  9984. assert(E->isLValue() && E->getType().isConstQualified());
  9985. E = E->IgnoreParens();
  9986. // Must be a reference to a declaration from an enclosing scope.
  9987. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  9988. if (!DRE) return NCCK_None;
  9989. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  9990. // The declaration must be a variable which is not declared 'const'.
  9991. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  9992. if (!var) return NCCK_None;
  9993. if (var->getType().isConstQualified()) return NCCK_None;
  9994. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  9995. // Decide whether the first capture was for a block or a lambda.
  9996. DeclContext *DC = S.CurContext, *Prev = nullptr;
  9997. // Decide whether the first capture was for a block or a lambda.
  9998. while (DC) {
  9999. // For init-capture, it is possible that the variable belongs to the
  10000. // template pattern of the current context.
  10001. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  10002. if (var->isInitCapture() &&
  10003. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  10004. break;
  10005. if (DC == var->getDeclContext())
  10006. break;
  10007. Prev = DC;
  10008. DC = DC->getParent();
  10009. }
  10010. // Unless we have an init-capture, we've gone one step too far.
  10011. if (!var->isInitCapture())
  10012. DC = Prev;
  10013. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  10014. }
  10015. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  10016. Ty = Ty.getNonReferenceType();
  10017. if (IsDereference && Ty->isPointerType())
  10018. Ty = Ty->getPointeeType();
  10019. return !Ty.isConstQualified();
  10020. }
  10021. // Update err_typecheck_assign_const and note_typecheck_assign_const
  10022. // when this enum is changed.
  10023. enum {
  10024. ConstFunction,
  10025. ConstVariable,
  10026. ConstMember,
  10027. ConstMethod,
  10028. NestedConstMember,
  10029. ConstUnknown, // Keep as last element
  10030. };
  10031. /// Emit the "read-only variable not assignable" error and print notes to give
  10032. /// more information about why the variable is not assignable, such as pointing
  10033. /// to the declaration of a const variable, showing that a method is const, or
  10034. /// that the function is returning a const reference.
  10035. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  10036. SourceLocation Loc) {
  10037. SourceRange ExprRange = E->getSourceRange();
  10038. // Only emit one error on the first const found. All other consts will emit
  10039. // a note to the error.
  10040. bool DiagnosticEmitted = false;
  10041. // Track if the current expression is the result of a dereference, and if the
  10042. // next checked expression is the result of a dereference.
  10043. bool IsDereference = false;
  10044. bool NextIsDereference = false;
  10045. // Loop to process MemberExpr chains.
  10046. while (true) {
  10047. IsDereference = NextIsDereference;
  10048. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  10049. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  10050. NextIsDereference = ME->isArrow();
  10051. const ValueDecl *VD = ME->getMemberDecl();
  10052. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  10053. // Mutable fields can be modified even if the class is const.
  10054. if (Field->isMutable()) {
  10055. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  10056. break;
  10057. }
  10058. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  10059. if (!DiagnosticEmitted) {
  10060. S.Diag(Loc, diag::err_typecheck_assign_const)
  10061. << ExprRange << ConstMember << false /*static*/ << Field
  10062. << Field->getType();
  10063. DiagnosticEmitted = true;
  10064. }
  10065. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10066. << ConstMember << false /*static*/ << Field << Field->getType()
  10067. << Field->getSourceRange();
  10068. }
  10069. E = ME->getBase();
  10070. continue;
  10071. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  10072. if (VDecl->getType().isConstQualified()) {
  10073. if (!DiagnosticEmitted) {
  10074. S.Diag(Loc, diag::err_typecheck_assign_const)
  10075. << ExprRange << ConstMember << true /*static*/ << VDecl
  10076. << VDecl->getType();
  10077. DiagnosticEmitted = true;
  10078. }
  10079. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10080. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  10081. << VDecl->getSourceRange();
  10082. }
  10083. // Static fields do not inherit constness from parents.
  10084. break;
  10085. }
  10086. break; // End MemberExpr
  10087. } else if (const ArraySubscriptExpr *ASE =
  10088. dyn_cast<ArraySubscriptExpr>(E)) {
  10089. E = ASE->getBase()->IgnoreParenImpCasts();
  10090. continue;
  10091. } else if (const ExtVectorElementExpr *EVE =
  10092. dyn_cast<ExtVectorElementExpr>(E)) {
  10093. E = EVE->getBase()->IgnoreParenImpCasts();
  10094. continue;
  10095. }
  10096. break;
  10097. }
  10098. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  10099. // Function calls
  10100. const FunctionDecl *FD = CE->getDirectCallee();
  10101. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  10102. if (!DiagnosticEmitted) {
  10103. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10104. << ConstFunction << FD;
  10105. DiagnosticEmitted = true;
  10106. }
  10107. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  10108. diag::note_typecheck_assign_const)
  10109. << ConstFunction << FD << FD->getReturnType()
  10110. << FD->getReturnTypeSourceRange();
  10111. }
  10112. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10113. // Point to variable declaration.
  10114. if (const ValueDecl *VD = DRE->getDecl()) {
  10115. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  10116. if (!DiagnosticEmitted) {
  10117. S.Diag(Loc, diag::err_typecheck_assign_const)
  10118. << ExprRange << ConstVariable << VD << VD->getType();
  10119. DiagnosticEmitted = true;
  10120. }
  10121. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  10122. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  10123. }
  10124. }
  10125. } else if (isa<CXXThisExpr>(E)) {
  10126. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  10127. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  10128. if (MD->isConst()) {
  10129. if (!DiagnosticEmitted) {
  10130. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  10131. << ConstMethod << MD;
  10132. DiagnosticEmitted = true;
  10133. }
  10134. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  10135. << ConstMethod << MD << MD->getSourceRange();
  10136. }
  10137. }
  10138. }
  10139. }
  10140. if (DiagnosticEmitted)
  10141. return;
  10142. // Can't determine a more specific message, so display the generic error.
  10143. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  10144. }
  10145. enum OriginalExprKind {
  10146. OEK_Variable,
  10147. OEK_Member,
  10148. OEK_LValue
  10149. };
  10150. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  10151. const RecordType *Ty,
  10152. SourceLocation Loc, SourceRange Range,
  10153. OriginalExprKind OEK,
  10154. bool &DiagnosticEmitted) {
  10155. std::vector<const RecordType *> RecordTypeList;
  10156. RecordTypeList.push_back(Ty);
  10157. unsigned NextToCheckIndex = 0;
  10158. // We walk the record hierarchy breadth-first to ensure that we print
  10159. // diagnostics in field nesting order.
  10160. while (RecordTypeList.size() > NextToCheckIndex) {
  10161. bool IsNested = NextToCheckIndex > 0;
  10162. for (const FieldDecl *Field :
  10163. RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
  10164. // First, check every field for constness.
  10165. QualType FieldTy = Field->getType();
  10166. if (FieldTy.isConstQualified()) {
  10167. if (!DiagnosticEmitted) {
  10168. S.Diag(Loc, diag::err_typecheck_assign_const)
  10169. << Range << NestedConstMember << OEK << VD
  10170. << IsNested << Field;
  10171. DiagnosticEmitted = true;
  10172. }
  10173. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  10174. << NestedConstMember << IsNested << Field
  10175. << FieldTy << Field->getSourceRange();
  10176. }
  10177. // Then we append it to the list to check next in order.
  10178. FieldTy = FieldTy.getCanonicalType();
  10179. if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
  10180. if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
  10181. RecordTypeList.push_back(FieldRecTy);
  10182. }
  10183. }
  10184. ++NextToCheckIndex;
  10185. }
  10186. }
  10187. /// Emit an error for the case where a record we are trying to assign to has a
  10188. /// const-qualified field somewhere in its hierarchy.
  10189. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  10190. SourceLocation Loc) {
  10191. QualType Ty = E->getType();
  10192. assert(Ty->isRecordType() && "lvalue was not record?");
  10193. SourceRange Range = E->getSourceRange();
  10194. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  10195. bool DiagEmitted = false;
  10196. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  10197. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  10198. Range, OEK_Member, DiagEmitted);
  10199. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  10200. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  10201. Range, OEK_Variable, DiagEmitted);
  10202. else
  10203. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  10204. Range, OEK_LValue, DiagEmitted);
  10205. if (!DiagEmitted)
  10206. DiagnoseConstAssignment(S, E, Loc);
  10207. }
  10208. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  10209. /// emit an error and return true. If so, return false.
  10210. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  10211. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  10212. S.CheckShadowingDeclModification(E, Loc);
  10213. SourceLocation OrigLoc = Loc;
  10214. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  10215. &Loc);
  10216. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  10217. IsLV = Expr::MLV_InvalidMessageExpression;
  10218. if (IsLV == Expr::MLV_Valid)
  10219. return false;
  10220. unsigned DiagID = 0;
  10221. bool NeedType = false;
  10222. switch (IsLV) { // C99 6.5.16p2
  10223. case Expr::MLV_ConstQualified:
  10224. // Use a specialized diagnostic when we're assigning to an object
  10225. // from an enclosing function or block.
  10226. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  10227. if (NCCK == NCCK_Block)
  10228. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  10229. else
  10230. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  10231. break;
  10232. }
  10233. // In ARC, use some specialized diagnostics for occasions where we
  10234. // infer 'const'. These are always pseudo-strong variables.
  10235. if (S.getLangOpts().ObjCAutoRefCount) {
  10236. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  10237. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  10238. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  10239. // Use the normal diagnostic if it's pseudo-__strong but the
  10240. // user actually wrote 'const'.
  10241. if (var->isARCPseudoStrong() &&
  10242. (!var->getTypeSourceInfo() ||
  10243. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  10244. // There are three pseudo-strong cases:
  10245. // - self
  10246. ObjCMethodDecl *method = S.getCurMethodDecl();
  10247. if (method && var == method->getSelfDecl()) {
  10248. DiagID = method->isClassMethod()
  10249. ? diag::err_typecheck_arc_assign_self_class_method
  10250. : diag::err_typecheck_arc_assign_self;
  10251. // - Objective-C externally_retained attribute.
  10252. } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
  10253. isa<ParmVarDecl>(var)) {
  10254. DiagID = diag::err_typecheck_arc_assign_externally_retained;
  10255. // - fast enumeration variables
  10256. } else {
  10257. DiagID = diag::err_typecheck_arr_assign_enumeration;
  10258. }
  10259. SourceRange Assign;
  10260. if (Loc != OrigLoc)
  10261. Assign = SourceRange(OrigLoc, OrigLoc);
  10262. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10263. // We need to preserve the AST regardless, so migration tool
  10264. // can do its job.
  10265. return false;
  10266. }
  10267. }
  10268. }
  10269. // If none of the special cases above are triggered, then this is a
  10270. // simple const assignment.
  10271. if (DiagID == 0) {
  10272. DiagnoseConstAssignment(S, E, Loc);
  10273. return true;
  10274. }
  10275. break;
  10276. case Expr::MLV_ConstAddrSpace:
  10277. DiagnoseConstAssignment(S, E, Loc);
  10278. return true;
  10279. case Expr::MLV_ConstQualifiedField:
  10280. DiagnoseRecursiveConstFields(S, E, Loc);
  10281. return true;
  10282. case Expr::MLV_ArrayType:
  10283. case Expr::MLV_ArrayTemporary:
  10284. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  10285. NeedType = true;
  10286. break;
  10287. case Expr::MLV_NotObjectType:
  10288. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  10289. NeedType = true;
  10290. break;
  10291. case Expr::MLV_LValueCast:
  10292. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  10293. break;
  10294. case Expr::MLV_Valid:
  10295. llvm_unreachable("did not take early return for MLV_Valid");
  10296. case Expr::MLV_InvalidExpression:
  10297. case Expr::MLV_MemberFunction:
  10298. case Expr::MLV_ClassTemporary:
  10299. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  10300. break;
  10301. case Expr::MLV_IncompleteType:
  10302. case Expr::MLV_IncompleteVoidType:
  10303. return S.RequireCompleteType(Loc, E->getType(),
  10304. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  10305. case Expr::MLV_DuplicateVectorComponents:
  10306. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  10307. break;
  10308. case Expr::MLV_NoSetterProperty:
  10309. llvm_unreachable("readonly properties should be processed differently");
  10310. case Expr::MLV_InvalidMessageExpression:
  10311. DiagID = diag::err_readonly_message_assignment;
  10312. break;
  10313. case Expr::MLV_SubObjCPropertySetting:
  10314. DiagID = diag::err_no_subobject_property_setting;
  10315. break;
  10316. }
  10317. SourceRange Assign;
  10318. if (Loc != OrigLoc)
  10319. Assign = SourceRange(OrigLoc, OrigLoc);
  10320. if (NeedType)
  10321. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  10322. else
  10323. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  10324. return true;
  10325. }
  10326. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  10327. SourceLocation Loc,
  10328. Sema &Sema) {
  10329. if (Sema.inTemplateInstantiation())
  10330. return;
  10331. if (Sema.isUnevaluatedContext())
  10332. return;
  10333. if (Loc.isInvalid() || Loc.isMacroID())
  10334. return;
  10335. if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
  10336. return;
  10337. // C / C++ fields
  10338. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  10339. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  10340. if (ML && MR) {
  10341. if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
  10342. return;
  10343. const ValueDecl *LHSDecl =
  10344. cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
  10345. const ValueDecl *RHSDecl =
  10346. cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
  10347. if (LHSDecl != RHSDecl)
  10348. return;
  10349. if (LHSDecl->getType().isVolatileQualified())
  10350. return;
  10351. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10352. if (RefTy->getPointeeType().isVolatileQualified())
  10353. return;
  10354. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  10355. }
  10356. // Objective-C instance variables
  10357. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  10358. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  10359. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  10360. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  10361. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  10362. if (RL && RR && RL->getDecl() == RR->getDecl())
  10363. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  10364. }
  10365. }
  10366. // C99 6.5.16.1
  10367. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  10368. SourceLocation Loc,
  10369. QualType CompoundType) {
  10370. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  10371. // Verify that LHS is a modifiable lvalue, and emit error if not.
  10372. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  10373. return QualType();
  10374. QualType LHSType = LHSExpr->getType();
  10375. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  10376. CompoundType;
  10377. // OpenCL v1.2 s6.1.1.1 p2:
  10378. // The half data type can only be used to declare a pointer to a buffer that
  10379. // contains half values
  10380. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  10381. LHSType->isHalfType()) {
  10382. Diag(Loc, diag::err_opencl_half_load_store) << 1
  10383. << LHSType.getUnqualifiedType();
  10384. return QualType();
  10385. }
  10386. AssignConvertType ConvTy;
  10387. if (CompoundType.isNull()) {
  10388. Expr *RHSCheck = RHS.get();
  10389. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  10390. QualType LHSTy(LHSType);
  10391. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  10392. if (RHS.isInvalid())
  10393. return QualType();
  10394. // Special case of NSObject attributes on c-style pointer types.
  10395. if (ConvTy == IncompatiblePointer &&
  10396. ((Context.isObjCNSObjectType(LHSType) &&
  10397. RHSType->isObjCObjectPointerType()) ||
  10398. (Context.isObjCNSObjectType(RHSType) &&
  10399. LHSType->isObjCObjectPointerType())))
  10400. ConvTy = Compatible;
  10401. if (ConvTy == Compatible &&
  10402. LHSType->isObjCObjectType())
  10403. Diag(Loc, diag::err_objc_object_assignment)
  10404. << LHSType;
  10405. // If the RHS is a unary plus or minus, check to see if they = and + are
  10406. // right next to each other. If so, the user may have typo'd "x =+ 4"
  10407. // instead of "x += 4".
  10408. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  10409. RHSCheck = ICE->getSubExpr();
  10410. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  10411. if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
  10412. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  10413. // Only if the two operators are exactly adjacent.
  10414. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  10415. // And there is a space or other character before the subexpr of the
  10416. // unary +/-. We don't want to warn on "x=-1".
  10417. Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
  10418. UO->getSubExpr()->getBeginLoc().isFileID()) {
  10419. Diag(Loc, diag::warn_not_compound_assign)
  10420. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  10421. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  10422. }
  10423. }
  10424. if (ConvTy == Compatible) {
  10425. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  10426. // Warn about retain cycles where a block captures the LHS, but
  10427. // not if the LHS is a simple variable into which the block is
  10428. // being stored...unless that variable can be captured by reference!
  10429. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  10430. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  10431. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  10432. checkRetainCycles(LHSExpr, RHS.get());
  10433. }
  10434. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  10435. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  10436. // It is safe to assign a weak reference into a strong variable.
  10437. // Although this code can still have problems:
  10438. // id x = self.weakProp;
  10439. // id y = self.weakProp;
  10440. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10441. // paths through the function. This should be revisited if
  10442. // -Wrepeated-use-of-weak is made flow-sensitive.
  10443. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  10444. // variable, which will be valid for the current autorelease scope.
  10445. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10446. RHS.get()->getBeginLoc()))
  10447. getCurFunction()->markSafeWeakUse(RHS.get());
  10448. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  10449. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  10450. }
  10451. }
  10452. } else {
  10453. // Compound assignment "x += y"
  10454. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  10455. }
  10456. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  10457. RHS.get(), AA_Assigning))
  10458. return QualType();
  10459. CheckForNullPointerDereference(*this, LHSExpr);
  10460. // C99 6.5.16p3: The type of an assignment expression is the type of the
  10461. // left operand unless the left operand has qualified type, in which case
  10462. // it is the unqualified version of the type of the left operand.
  10463. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  10464. // is converted to the type of the assignment expression (above).
  10465. // C++ 5.17p1: the type of the assignment expression is that of its left
  10466. // operand.
  10467. return (getLangOpts().CPlusPlus
  10468. ? LHSType : LHSType.getUnqualifiedType());
  10469. }
  10470. // Only ignore explicit casts to void.
  10471. static bool IgnoreCommaOperand(const Expr *E) {
  10472. E = E->IgnoreParens();
  10473. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  10474. if (CE->getCastKind() == CK_ToVoid) {
  10475. return true;
  10476. }
  10477. // static_cast<void> on a dependent type will not show up as CK_ToVoid.
  10478. if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
  10479. CE->getSubExpr()->getType()->isDependentType()) {
  10480. return true;
  10481. }
  10482. }
  10483. return false;
  10484. }
  10485. // Look for instances where it is likely the comma operator is confused with
  10486. // another operator. There is a whitelist of acceptable expressions for the
  10487. // left hand side of the comma operator, otherwise emit a warning.
  10488. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  10489. // No warnings in macros
  10490. if (Loc.isMacroID())
  10491. return;
  10492. // Don't warn in template instantiations.
  10493. if (inTemplateInstantiation())
  10494. return;
  10495. // Scope isn't fine-grained enough to whitelist the specific cases, so
  10496. // instead, skip more than needed, then call back into here with the
  10497. // CommaVisitor in SemaStmt.cpp.
  10498. // The whitelisted locations are the initialization and increment portions
  10499. // of a for loop. The additional checks are on the condition of
  10500. // if statements, do/while loops, and for loops.
  10501. // Differences in scope flags for C89 mode requires the extra logic.
  10502. const unsigned ForIncrementFlags =
  10503. getLangOpts().C99 || getLangOpts().CPlusPlus
  10504. ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
  10505. : Scope::ContinueScope | Scope::BreakScope;
  10506. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  10507. const unsigned ScopeFlags = getCurScope()->getFlags();
  10508. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  10509. (ScopeFlags & ForInitFlags) == ForInitFlags)
  10510. return;
  10511. // If there are multiple comma operators used together, get the RHS of the
  10512. // of the comma operator as the LHS.
  10513. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  10514. if (BO->getOpcode() != BO_Comma)
  10515. break;
  10516. LHS = BO->getRHS();
  10517. }
  10518. // Only allow some expressions on LHS to not warn.
  10519. if (IgnoreCommaOperand(LHS))
  10520. return;
  10521. Diag(Loc, diag::warn_comma_operator);
  10522. Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
  10523. << LHS->getSourceRange()
  10524. << FixItHint::CreateInsertion(LHS->getBeginLoc(),
  10525. LangOpts.CPlusPlus ? "static_cast<void>("
  10526. : "(void)(")
  10527. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
  10528. ")");
  10529. }
  10530. // C99 6.5.17
  10531. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  10532. SourceLocation Loc) {
  10533. LHS = S.CheckPlaceholderExpr(LHS.get());
  10534. RHS = S.CheckPlaceholderExpr(RHS.get());
  10535. if (LHS.isInvalid() || RHS.isInvalid())
  10536. return QualType();
  10537. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  10538. // operands, but not unary promotions.
  10539. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  10540. // So we treat the LHS as a ignored value, and in C++ we allow the
  10541. // containing site to determine what should be done with the RHS.
  10542. LHS = S.IgnoredValueConversions(LHS.get());
  10543. if (LHS.isInvalid())
  10544. return QualType();
  10545. S.DiagnoseUnusedExprResult(LHS.get());
  10546. if (!S.getLangOpts().CPlusPlus) {
  10547. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  10548. if (RHS.isInvalid())
  10549. return QualType();
  10550. if (!RHS.get()->getType()->isVoidType())
  10551. S.RequireCompleteType(Loc, RHS.get()->getType(),
  10552. diag::err_incomplete_type);
  10553. }
  10554. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  10555. S.DiagnoseCommaOperator(LHS.get(), Loc);
  10556. return RHS.get()->getType();
  10557. }
  10558. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  10559. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  10560. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  10561. ExprValueKind &VK,
  10562. ExprObjectKind &OK,
  10563. SourceLocation OpLoc,
  10564. bool IsInc, bool IsPrefix) {
  10565. if (Op->isTypeDependent())
  10566. return S.Context.DependentTy;
  10567. QualType ResType = Op->getType();
  10568. // Atomic types can be used for increment / decrement where the non-atomic
  10569. // versions can, so ignore the _Atomic() specifier for the purpose of
  10570. // checking.
  10571. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  10572. ResType = ResAtomicType->getValueType();
  10573. assert(!ResType.isNull() && "no type for increment/decrement expression");
  10574. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  10575. // Decrement of bool is not allowed.
  10576. if (!IsInc) {
  10577. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  10578. return QualType();
  10579. }
  10580. // Increment of bool sets it to true, but is deprecated.
  10581. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  10582. : diag::warn_increment_bool)
  10583. << Op->getSourceRange();
  10584. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  10585. // Error on enum increments and decrements in C++ mode
  10586. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  10587. return QualType();
  10588. } else if (ResType->isRealType()) {
  10589. // OK!
  10590. } else if (ResType->isPointerType()) {
  10591. // C99 6.5.2.4p2, 6.5.6p2
  10592. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  10593. return QualType();
  10594. } else if (ResType->isObjCObjectPointerType()) {
  10595. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  10596. // Otherwise, we just need a complete type.
  10597. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  10598. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  10599. return QualType();
  10600. } else if (ResType->isAnyComplexType()) {
  10601. // C99 does not support ++/-- on complex types, we allow as an extension.
  10602. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  10603. << ResType << Op->getSourceRange();
  10604. } else if (ResType->isPlaceholderType()) {
  10605. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10606. if (PR.isInvalid()) return QualType();
  10607. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  10608. IsInc, IsPrefix);
  10609. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  10610. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  10611. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  10612. (ResType->getAs<VectorType>()->getVectorKind() !=
  10613. VectorType::AltiVecBool)) {
  10614. // The z vector extensions allow ++ and -- for non-bool vectors.
  10615. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  10616. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  10617. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  10618. } else {
  10619. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  10620. << ResType << int(IsInc) << Op->getSourceRange();
  10621. return QualType();
  10622. }
  10623. // At this point, we know we have a real, complex or pointer type.
  10624. // Now make sure the operand is a modifiable lvalue.
  10625. if (CheckForModifiableLvalue(Op, OpLoc, S))
  10626. return QualType();
  10627. // In C++, a prefix increment is the same type as the operand. Otherwise
  10628. // (in C or with postfix), the increment is the unqualified type of the
  10629. // operand.
  10630. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  10631. VK = VK_LValue;
  10632. OK = Op->getObjectKind();
  10633. return ResType;
  10634. } else {
  10635. VK = VK_RValue;
  10636. return ResType.getUnqualifiedType();
  10637. }
  10638. }
  10639. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  10640. /// This routine allows us to typecheck complex/recursive expressions
  10641. /// where the declaration is needed for type checking. We only need to
  10642. /// handle cases when the expression references a function designator
  10643. /// or is an lvalue. Here are some examples:
  10644. /// - &(x) => x
  10645. /// - &*****f => f for f a function designator.
  10646. /// - &s.xx => s
  10647. /// - &s.zz[1].yy -> s, if zz is an array
  10648. /// - *(x + 1) -> x, if x is an array
  10649. /// - &"123"[2] -> 0
  10650. /// - & __real__ x -> x
  10651. static ValueDecl *getPrimaryDecl(Expr *E) {
  10652. switch (E->getStmtClass()) {
  10653. case Stmt::DeclRefExprClass:
  10654. return cast<DeclRefExpr>(E)->getDecl();
  10655. case Stmt::MemberExprClass:
  10656. // If this is an arrow operator, the address is an offset from
  10657. // the base's value, so the object the base refers to is
  10658. // irrelevant.
  10659. if (cast<MemberExpr>(E)->isArrow())
  10660. return nullptr;
  10661. // Otherwise, the expression refers to a part of the base
  10662. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  10663. case Stmt::ArraySubscriptExprClass: {
  10664. // FIXME: This code shouldn't be necessary! We should catch the implicit
  10665. // promotion of register arrays earlier.
  10666. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  10667. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  10668. if (ICE->getSubExpr()->getType()->isArrayType())
  10669. return getPrimaryDecl(ICE->getSubExpr());
  10670. }
  10671. return nullptr;
  10672. }
  10673. case Stmt::UnaryOperatorClass: {
  10674. UnaryOperator *UO = cast<UnaryOperator>(E);
  10675. switch(UO->getOpcode()) {
  10676. case UO_Real:
  10677. case UO_Imag:
  10678. case UO_Extension:
  10679. return getPrimaryDecl(UO->getSubExpr());
  10680. default:
  10681. return nullptr;
  10682. }
  10683. }
  10684. case Stmt::ParenExprClass:
  10685. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  10686. case Stmt::ImplicitCastExprClass:
  10687. // If the result of an implicit cast is an l-value, we care about
  10688. // the sub-expression; otherwise, the result here doesn't matter.
  10689. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  10690. default:
  10691. return nullptr;
  10692. }
  10693. }
  10694. namespace {
  10695. enum {
  10696. AO_Bit_Field = 0,
  10697. AO_Vector_Element = 1,
  10698. AO_Property_Expansion = 2,
  10699. AO_Register_Variable = 3,
  10700. AO_No_Error = 4
  10701. };
  10702. }
  10703. /// Diagnose invalid operand for address of operations.
  10704. ///
  10705. /// \param Type The type of operand which cannot have its address taken.
  10706. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  10707. Expr *E, unsigned Type) {
  10708. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  10709. }
  10710. /// CheckAddressOfOperand - The operand of & must be either a function
  10711. /// designator or an lvalue designating an object. If it is an lvalue, the
  10712. /// object cannot be declared with storage class register or be a bit field.
  10713. /// Note: The usual conversions are *not* applied to the operand of the &
  10714. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  10715. /// In C++, the operand might be an overloaded function name, in which case
  10716. /// we allow the '&' but retain the overloaded-function type.
  10717. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  10718. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  10719. if (PTy->getKind() == BuiltinType::Overload) {
  10720. Expr *E = OrigOp.get()->IgnoreParens();
  10721. if (!isa<OverloadExpr>(E)) {
  10722. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  10723. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  10724. << OrigOp.get()->getSourceRange();
  10725. return QualType();
  10726. }
  10727. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  10728. if (isa<UnresolvedMemberExpr>(Ovl))
  10729. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  10730. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10731. << OrigOp.get()->getSourceRange();
  10732. return QualType();
  10733. }
  10734. return Context.OverloadTy;
  10735. }
  10736. if (PTy->getKind() == BuiltinType::UnknownAny)
  10737. return Context.UnknownAnyTy;
  10738. if (PTy->getKind() == BuiltinType::BoundMember) {
  10739. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10740. << OrigOp.get()->getSourceRange();
  10741. return QualType();
  10742. }
  10743. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  10744. if (OrigOp.isInvalid()) return QualType();
  10745. }
  10746. if (OrigOp.get()->isTypeDependent())
  10747. return Context.DependentTy;
  10748. assert(!OrigOp.get()->getType()->isPlaceholderType());
  10749. // Make sure to ignore parentheses in subsequent checks
  10750. Expr *op = OrigOp.get()->IgnoreParens();
  10751. // In OpenCL captures for blocks called as lambda functions
  10752. // are located in the private address space. Blocks used in
  10753. // enqueue_kernel can be located in a different address space
  10754. // depending on a vendor implementation. Thus preventing
  10755. // taking an address of the capture to avoid invalid AS casts.
  10756. if (LangOpts.OpenCL) {
  10757. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  10758. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  10759. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  10760. return QualType();
  10761. }
  10762. }
  10763. if (getLangOpts().C99) {
  10764. // Implement C99-only parts of addressof rules.
  10765. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  10766. if (uOp->getOpcode() == UO_Deref)
  10767. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  10768. // (assuming the deref expression is valid).
  10769. return uOp->getSubExpr()->getType();
  10770. }
  10771. // Technically, there should be a check for array subscript
  10772. // expressions here, but the result of one is always an lvalue anyway.
  10773. }
  10774. ValueDecl *dcl = getPrimaryDecl(op);
  10775. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  10776. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  10777. op->getBeginLoc()))
  10778. return QualType();
  10779. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  10780. unsigned AddressOfError = AO_No_Error;
  10781. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  10782. bool sfinae = (bool)isSFINAEContext();
  10783. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  10784. : diag::ext_typecheck_addrof_temporary)
  10785. << op->getType() << op->getSourceRange();
  10786. if (sfinae)
  10787. return QualType();
  10788. // Materialize the temporary as an lvalue so that we can take its address.
  10789. OrigOp = op =
  10790. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  10791. } else if (isa<ObjCSelectorExpr>(op)) {
  10792. return Context.getPointerType(op->getType());
  10793. } else if (lval == Expr::LV_MemberFunction) {
  10794. // If it's an instance method, make a member pointer.
  10795. // The expression must have exactly the form &A::foo.
  10796. // If the underlying expression isn't a decl ref, give up.
  10797. if (!isa<DeclRefExpr>(op)) {
  10798. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  10799. << OrigOp.get()->getSourceRange();
  10800. return QualType();
  10801. }
  10802. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  10803. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  10804. // The id-expression was parenthesized.
  10805. if (OrigOp.get() != DRE) {
  10806. Diag(OpLoc, diag::err_parens_pointer_member_function)
  10807. << OrigOp.get()->getSourceRange();
  10808. // The method was named without a qualifier.
  10809. } else if (!DRE->getQualifier()) {
  10810. if (MD->getParent()->getName().empty())
  10811. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10812. << op->getSourceRange();
  10813. else {
  10814. SmallString<32> Str;
  10815. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  10816. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  10817. << op->getSourceRange()
  10818. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  10819. }
  10820. }
  10821. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  10822. if (isa<CXXDestructorDecl>(MD))
  10823. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  10824. QualType MPTy = Context.getMemberPointerType(
  10825. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  10826. // Under the MS ABI, lock down the inheritance model now.
  10827. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10828. (void)isCompleteType(OpLoc, MPTy);
  10829. return MPTy;
  10830. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  10831. // C99 6.5.3.2p1
  10832. // The operand must be either an l-value or a function designator
  10833. if (!op->getType()->isFunctionType()) {
  10834. // Use a special diagnostic for loads from property references.
  10835. if (isa<PseudoObjectExpr>(op)) {
  10836. AddressOfError = AO_Property_Expansion;
  10837. } else {
  10838. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  10839. << op->getType() << op->getSourceRange();
  10840. return QualType();
  10841. }
  10842. }
  10843. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  10844. // The operand cannot be a bit-field
  10845. AddressOfError = AO_Bit_Field;
  10846. } else if (op->getObjectKind() == OK_VectorComponent) {
  10847. // The operand cannot be an element of a vector
  10848. AddressOfError = AO_Vector_Element;
  10849. } else if (dcl) { // C99 6.5.3.2p1
  10850. // We have an lvalue with a decl. Make sure the decl is not declared
  10851. // with the register storage-class specifier.
  10852. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  10853. // in C++ it is not error to take address of a register
  10854. // variable (c++03 7.1.1P3)
  10855. if (vd->getStorageClass() == SC_Register &&
  10856. !getLangOpts().CPlusPlus) {
  10857. AddressOfError = AO_Register_Variable;
  10858. }
  10859. } else if (isa<MSPropertyDecl>(dcl)) {
  10860. AddressOfError = AO_Property_Expansion;
  10861. } else if (isa<FunctionTemplateDecl>(dcl)) {
  10862. return Context.OverloadTy;
  10863. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  10864. // Okay: we can take the address of a field.
  10865. // Could be a pointer to member, though, if there is an explicit
  10866. // scope qualifier for the class.
  10867. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  10868. DeclContext *Ctx = dcl->getDeclContext();
  10869. if (Ctx && Ctx->isRecord()) {
  10870. if (dcl->getType()->isReferenceType()) {
  10871. Diag(OpLoc,
  10872. diag::err_cannot_form_pointer_to_member_of_reference_type)
  10873. << dcl->getDeclName() << dcl->getType();
  10874. return QualType();
  10875. }
  10876. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  10877. Ctx = Ctx->getParent();
  10878. QualType MPTy = Context.getMemberPointerType(
  10879. op->getType(),
  10880. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  10881. // Under the MS ABI, lock down the inheritance model now.
  10882. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  10883. (void)isCompleteType(OpLoc, MPTy);
  10884. return MPTy;
  10885. }
  10886. }
  10887. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  10888. !isa<BindingDecl>(dcl))
  10889. llvm_unreachable("Unknown/unexpected decl type");
  10890. }
  10891. if (AddressOfError != AO_No_Error) {
  10892. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  10893. return QualType();
  10894. }
  10895. if (lval == Expr::LV_IncompleteVoidType) {
  10896. // Taking the address of a void variable is technically illegal, but we
  10897. // allow it in cases which are otherwise valid.
  10898. // Example: "extern void x; void* y = &x;".
  10899. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  10900. }
  10901. // If the operand has type "type", the result has type "pointer to type".
  10902. if (op->getType()->isObjCObjectType())
  10903. return Context.getObjCObjectPointerType(op->getType());
  10904. CheckAddressOfPackedMember(op);
  10905. return Context.getPointerType(op->getType());
  10906. }
  10907. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  10908. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  10909. if (!DRE)
  10910. return;
  10911. const Decl *D = DRE->getDecl();
  10912. if (!D)
  10913. return;
  10914. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  10915. if (!Param)
  10916. return;
  10917. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  10918. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  10919. return;
  10920. if (FunctionScopeInfo *FD = S.getCurFunction())
  10921. if (!FD->ModifiedNonNullParams.count(Param))
  10922. FD->ModifiedNonNullParams.insert(Param);
  10923. }
  10924. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  10925. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  10926. SourceLocation OpLoc) {
  10927. if (Op->isTypeDependent())
  10928. return S.Context.DependentTy;
  10929. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  10930. if (ConvResult.isInvalid())
  10931. return QualType();
  10932. Op = ConvResult.get();
  10933. QualType OpTy = Op->getType();
  10934. QualType Result;
  10935. if (isa<CXXReinterpretCastExpr>(Op)) {
  10936. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  10937. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  10938. Op->getSourceRange());
  10939. }
  10940. if (const PointerType *PT = OpTy->getAs<PointerType>())
  10941. {
  10942. Result = PT->getPointeeType();
  10943. }
  10944. else if (const ObjCObjectPointerType *OPT =
  10945. OpTy->getAs<ObjCObjectPointerType>())
  10946. Result = OPT->getPointeeType();
  10947. else {
  10948. ExprResult PR = S.CheckPlaceholderExpr(Op);
  10949. if (PR.isInvalid()) return QualType();
  10950. if (PR.get() != Op)
  10951. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  10952. }
  10953. if (Result.isNull()) {
  10954. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  10955. << OpTy << Op->getSourceRange();
  10956. return QualType();
  10957. }
  10958. // Note that per both C89 and C99, indirection is always legal, even if Result
  10959. // is an incomplete type or void. It would be possible to warn about
  10960. // dereferencing a void pointer, but it's completely well-defined, and such a
  10961. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  10962. // for pointers to 'void' but is fine for any other pointer type:
  10963. //
  10964. // C++ [expr.unary.op]p1:
  10965. // [...] the expression to which [the unary * operator] is applied shall
  10966. // be a pointer to an object type, or a pointer to a function type
  10967. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  10968. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  10969. << OpTy << Op->getSourceRange();
  10970. // Dereferences are usually l-values...
  10971. VK = VK_LValue;
  10972. // ...except that certain expressions are never l-values in C.
  10973. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  10974. VK = VK_RValue;
  10975. return Result;
  10976. }
  10977. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  10978. BinaryOperatorKind Opc;
  10979. switch (Kind) {
  10980. default: llvm_unreachable("Unknown binop!");
  10981. case tok::periodstar: Opc = BO_PtrMemD; break;
  10982. case tok::arrowstar: Opc = BO_PtrMemI; break;
  10983. case tok::star: Opc = BO_Mul; break;
  10984. case tok::slash: Opc = BO_Div; break;
  10985. case tok::percent: Opc = BO_Rem; break;
  10986. case tok::plus: Opc = BO_Add; break;
  10987. case tok::minus: Opc = BO_Sub; break;
  10988. case tok::lessless: Opc = BO_Shl; break;
  10989. case tok::greatergreater: Opc = BO_Shr; break;
  10990. case tok::lessequal: Opc = BO_LE; break;
  10991. case tok::less: Opc = BO_LT; break;
  10992. case tok::greaterequal: Opc = BO_GE; break;
  10993. case tok::greater: Opc = BO_GT; break;
  10994. case tok::exclaimequal: Opc = BO_NE; break;
  10995. case tok::equalequal: Opc = BO_EQ; break;
  10996. case tok::spaceship: Opc = BO_Cmp; break;
  10997. case tok::amp: Opc = BO_And; break;
  10998. case tok::caret: Opc = BO_Xor; break;
  10999. case tok::pipe: Opc = BO_Or; break;
  11000. case tok::ampamp: Opc = BO_LAnd; break;
  11001. case tok::pipepipe: Opc = BO_LOr; break;
  11002. case tok::equal: Opc = BO_Assign; break;
  11003. case tok::starequal: Opc = BO_MulAssign; break;
  11004. case tok::slashequal: Opc = BO_DivAssign; break;
  11005. case tok::percentequal: Opc = BO_RemAssign; break;
  11006. case tok::plusequal: Opc = BO_AddAssign; break;
  11007. case tok::minusequal: Opc = BO_SubAssign; break;
  11008. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  11009. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  11010. case tok::ampequal: Opc = BO_AndAssign; break;
  11011. case tok::caretequal: Opc = BO_XorAssign; break;
  11012. case tok::pipeequal: Opc = BO_OrAssign; break;
  11013. case tok::comma: Opc = BO_Comma; break;
  11014. }
  11015. return Opc;
  11016. }
  11017. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  11018. tok::TokenKind Kind) {
  11019. UnaryOperatorKind Opc;
  11020. switch (Kind) {
  11021. default: llvm_unreachable("Unknown unary op!");
  11022. case tok::plusplus: Opc = UO_PreInc; break;
  11023. case tok::minusminus: Opc = UO_PreDec; break;
  11024. case tok::amp: Opc = UO_AddrOf; break;
  11025. case tok::star: Opc = UO_Deref; break;
  11026. case tok::plus: Opc = UO_Plus; break;
  11027. case tok::minus: Opc = UO_Minus; break;
  11028. case tok::tilde: Opc = UO_Not; break;
  11029. case tok::exclaim: Opc = UO_LNot; break;
  11030. case tok::kw___real: Opc = UO_Real; break;
  11031. case tok::kw___imag: Opc = UO_Imag; break;
  11032. case tok::kw___extension__: Opc = UO_Extension; break;
  11033. }
  11034. return Opc;
  11035. }
  11036. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  11037. /// This warning suppressed in the event of macro expansions.
  11038. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  11039. SourceLocation OpLoc, bool IsBuiltin) {
  11040. if (S.inTemplateInstantiation())
  11041. return;
  11042. if (S.isUnevaluatedContext())
  11043. return;
  11044. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  11045. return;
  11046. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  11047. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  11048. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  11049. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  11050. if (!LHSDeclRef || !RHSDeclRef ||
  11051. LHSDeclRef->getLocation().isMacroID() ||
  11052. RHSDeclRef->getLocation().isMacroID())
  11053. return;
  11054. const ValueDecl *LHSDecl =
  11055. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  11056. const ValueDecl *RHSDecl =
  11057. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  11058. if (LHSDecl != RHSDecl)
  11059. return;
  11060. if (LHSDecl->getType().isVolatileQualified())
  11061. return;
  11062. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  11063. if (RefTy->getPointeeType().isVolatileQualified())
  11064. return;
  11065. S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
  11066. : diag::warn_self_assignment_overloaded)
  11067. << LHSDeclRef->getType() << LHSExpr->getSourceRange()
  11068. << RHSExpr->getSourceRange();
  11069. }
  11070. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  11071. /// is usually indicative of introspection within the Objective-C pointer.
  11072. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  11073. SourceLocation OpLoc) {
  11074. if (!S.getLangOpts().ObjC)
  11075. return;
  11076. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  11077. const Expr *LHS = L.get();
  11078. const Expr *RHS = R.get();
  11079. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11080. ObjCPointerExpr = LHS;
  11081. OtherExpr = RHS;
  11082. }
  11083. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  11084. ObjCPointerExpr = RHS;
  11085. OtherExpr = LHS;
  11086. }
  11087. // This warning is deliberately made very specific to reduce false
  11088. // positives with logic that uses '&' for hashing. This logic mainly
  11089. // looks for code trying to introspect into tagged pointers, which
  11090. // code should generally never do.
  11091. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  11092. unsigned Diag = diag::warn_objc_pointer_masking;
  11093. // Determine if we are introspecting the result of performSelectorXXX.
  11094. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  11095. // Special case messages to -performSelector and friends, which
  11096. // can return non-pointer values boxed in a pointer value.
  11097. // Some clients may wish to silence warnings in this subcase.
  11098. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  11099. Selector S = ME->getSelector();
  11100. StringRef SelArg0 = S.getNameForSlot(0);
  11101. if (SelArg0.startswith("performSelector"))
  11102. Diag = diag::warn_objc_pointer_masking_performSelector;
  11103. }
  11104. S.Diag(OpLoc, Diag)
  11105. << ObjCPointerExpr->getSourceRange();
  11106. }
  11107. }
  11108. static NamedDecl *getDeclFromExpr(Expr *E) {
  11109. if (!E)
  11110. return nullptr;
  11111. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  11112. return DRE->getDecl();
  11113. if (auto *ME = dyn_cast<MemberExpr>(E))
  11114. return ME->getMemberDecl();
  11115. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  11116. return IRE->getDecl();
  11117. return nullptr;
  11118. }
  11119. // This helper function promotes a binary operator's operands (which are of a
  11120. // half vector type) to a vector of floats and then truncates the result to
  11121. // a vector of either half or short.
  11122. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  11123. BinaryOperatorKind Opc, QualType ResultTy,
  11124. ExprValueKind VK, ExprObjectKind OK,
  11125. bool IsCompAssign, SourceLocation OpLoc,
  11126. FPOptions FPFeatures) {
  11127. auto &Context = S.getASTContext();
  11128. assert((isVector(ResultTy, Context.HalfTy) ||
  11129. isVector(ResultTy, Context.ShortTy)) &&
  11130. "Result must be a vector of half or short");
  11131. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  11132. isVector(RHS.get()->getType(), Context.HalfTy) &&
  11133. "both operands expected to be a half vector");
  11134. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  11135. QualType BinOpResTy = RHS.get()->getType();
  11136. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  11137. // change BinOpResTy to a vector of ints.
  11138. if (isVector(ResultTy, Context.ShortTy))
  11139. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  11140. if (IsCompAssign)
  11141. return new (Context) CompoundAssignOperator(
  11142. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  11143. OpLoc, FPFeatures);
  11144. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  11145. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  11146. VK, OK, OpLoc, FPFeatures);
  11147. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  11148. }
  11149. static std::pair<ExprResult, ExprResult>
  11150. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  11151. Expr *RHSExpr) {
  11152. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11153. if (!S.getLangOpts().CPlusPlus) {
  11154. // C cannot handle TypoExpr nodes on either side of a binop because it
  11155. // doesn't handle dependent types properly, so make sure any TypoExprs have
  11156. // been dealt with before checking the operands.
  11157. LHS = S.CorrectDelayedTyposInExpr(LHS);
  11158. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  11159. if (Opc != BO_Assign)
  11160. return ExprResult(E);
  11161. // Avoid correcting the RHS to the same Expr as the LHS.
  11162. Decl *D = getDeclFromExpr(E);
  11163. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  11164. });
  11165. }
  11166. return std::make_pair(LHS, RHS);
  11167. }
  11168. /// Returns true if conversion between vectors of halfs and vectors of floats
  11169. /// is needed.
  11170. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  11171. QualType SrcType) {
  11172. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  11173. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  11174. isVector(SrcType, Ctx.HalfTy);
  11175. }
  11176. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  11177. /// operator @p Opc at location @c TokLoc. This routine only supports
  11178. /// built-in operations; ActOnBinOp handles overloaded operators.
  11179. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  11180. BinaryOperatorKind Opc,
  11181. Expr *LHSExpr, Expr *RHSExpr) {
  11182. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  11183. // The syntax only allows initializer lists on the RHS of assignment,
  11184. // so we don't need to worry about accepting invalid code for
  11185. // non-assignment operators.
  11186. // C++11 5.17p9:
  11187. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  11188. // of x = {} is x = T().
  11189. InitializationKind Kind = InitializationKind::CreateDirectList(
  11190. RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11191. InitializedEntity Entity =
  11192. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  11193. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  11194. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  11195. if (Init.isInvalid())
  11196. return Init;
  11197. RHSExpr = Init.get();
  11198. }
  11199. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  11200. QualType ResultTy; // Result type of the binary operator.
  11201. // The following two variables are used for compound assignment operators
  11202. QualType CompLHSTy; // Type of LHS after promotions for computation
  11203. QualType CompResultTy; // Type of computation result
  11204. ExprValueKind VK = VK_RValue;
  11205. ExprObjectKind OK = OK_Ordinary;
  11206. bool ConvertHalfVec = false;
  11207. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11208. if (!LHS.isUsable() || !RHS.isUsable())
  11209. return ExprError();
  11210. if (getLangOpts().OpenCL) {
  11211. QualType LHSTy = LHSExpr->getType();
  11212. QualType RHSTy = RHSExpr->getType();
  11213. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  11214. // the ATOMIC_VAR_INIT macro.
  11215. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  11216. SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
  11217. if (BO_Assign == Opc)
  11218. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  11219. else
  11220. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11221. return ExprError();
  11222. }
  11223. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11224. // only with a builtin functions and therefore should be disallowed here.
  11225. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  11226. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  11227. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  11228. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  11229. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  11230. return ExprError();
  11231. }
  11232. }
  11233. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11234. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11235. if (Opc != BO_Assign && Opc != BO_Comma) {
  11236. checkOpenMPDeviceExpr(LHSExpr);
  11237. checkOpenMPDeviceExpr(RHSExpr);
  11238. }
  11239. }
  11240. switch (Opc) {
  11241. case BO_Assign:
  11242. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  11243. if (getLangOpts().CPlusPlus &&
  11244. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  11245. VK = LHS.get()->getValueKind();
  11246. OK = LHS.get()->getObjectKind();
  11247. }
  11248. if (!ResultTy.isNull()) {
  11249. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11250. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  11251. // Avoid copying a block to the heap if the block is assigned to a local
  11252. // auto variable that is declared in the same scope as the block. This
  11253. // optimization is unsafe if the local variable is declared in an outer
  11254. // scope. For example:
  11255. //
  11256. // BlockTy b;
  11257. // {
  11258. // b = ^{...};
  11259. // }
  11260. // // It is unsafe to invoke the block here if it wasn't copied to the
  11261. // // heap.
  11262. // b();
  11263. if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
  11264. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
  11265. if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  11266. if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
  11267. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11268. }
  11269. RecordModifiableNonNullParam(*this, LHS.get());
  11270. break;
  11271. case BO_PtrMemD:
  11272. case BO_PtrMemI:
  11273. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  11274. Opc == BO_PtrMemI);
  11275. break;
  11276. case BO_Mul:
  11277. case BO_Div:
  11278. ConvertHalfVec = true;
  11279. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  11280. Opc == BO_Div);
  11281. break;
  11282. case BO_Rem:
  11283. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  11284. break;
  11285. case BO_Add:
  11286. ConvertHalfVec = true;
  11287. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  11288. break;
  11289. case BO_Sub:
  11290. ConvertHalfVec = true;
  11291. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  11292. break;
  11293. case BO_Shl:
  11294. case BO_Shr:
  11295. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  11296. break;
  11297. case BO_LE:
  11298. case BO_LT:
  11299. case BO_GE:
  11300. case BO_GT:
  11301. ConvertHalfVec = true;
  11302. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11303. break;
  11304. case BO_EQ:
  11305. case BO_NE:
  11306. ConvertHalfVec = true;
  11307. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11308. break;
  11309. case BO_Cmp:
  11310. ConvertHalfVec = true;
  11311. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
  11312. assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
  11313. break;
  11314. case BO_And:
  11315. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  11316. LLVM_FALLTHROUGH;
  11317. case BO_Xor:
  11318. case BO_Or:
  11319. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11320. break;
  11321. case BO_LAnd:
  11322. case BO_LOr:
  11323. ConvertHalfVec = true;
  11324. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  11325. break;
  11326. case BO_MulAssign:
  11327. case BO_DivAssign:
  11328. ConvertHalfVec = true;
  11329. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  11330. Opc == BO_DivAssign);
  11331. CompLHSTy = CompResultTy;
  11332. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11333. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11334. break;
  11335. case BO_RemAssign:
  11336. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  11337. CompLHSTy = CompResultTy;
  11338. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11339. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11340. break;
  11341. case BO_AddAssign:
  11342. ConvertHalfVec = true;
  11343. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  11344. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11345. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11346. break;
  11347. case BO_SubAssign:
  11348. ConvertHalfVec = true;
  11349. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  11350. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11351. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11352. break;
  11353. case BO_ShlAssign:
  11354. case BO_ShrAssign:
  11355. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  11356. CompLHSTy = CompResultTy;
  11357. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11358. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11359. break;
  11360. case BO_AndAssign:
  11361. case BO_OrAssign: // fallthrough
  11362. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
  11363. LLVM_FALLTHROUGH;
  11364. case BO_XorAssign:
  11365. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  11366. CompLHSTy = CompResultTy;
  11367. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  11368. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  11369. break;
  11370. case BO_Comma:
  11371. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  11372. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  11373. VK = RHS.get()->getValueKind();
  11374. OK = RHS.get()->getObjectKind();
  11375. }
  11376. break;
  11377. }
  11378. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  11379. return ExprError();
  11380. // Some of the binary operations require promoting operands of half vector to
  11381. // float vectors and truncating the result back to half vector. For now, we do
  11382. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  11383. // arm64).
  11384. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  11385. isVector(LHS.get()->getType(), Context.HalfTy) &&
  11386. "both sides are half vectors or neither sides are");
  11387. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  11388. LHS.get()->getType());
  11389. // Check for array bounds violations for both sides of the BinaryOperator
  11390. CheckArrayAccess(LHS.get());
  11391. CheckArrayAccess(RHS.get());
  11392. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  11393. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  11394. &Context.Idents.get("object_setClass"),
  11395. SourceLocation(), LookupOrdinaryName);
  11396. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  11397. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
  11398. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
  11399. << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
  11400. "object_setClass(")
  11401. << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
  11402. ",")
  11403. << FixItHint::CreateInsertion(RHSLocEnd, ")");
  11404. }
  11405. else
  11406. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  11407. }
  11408. else if (const ObjCIvarRefExpr *OIRE =
  11409. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  11410. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  11411. // Opc is not a compound assignment if CompResultTy is null.
  11412. if (CompResultTy.isNull()) {
  11413. if (ConvertHalfVec)
  11414. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  11415. OpLoc, FPFeatures);
  11416. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  11417. OK, OpLoc, FPFeatures);
  11418. }
  11419. // Handle compound assignments.
  11420. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  11421. OK_ObjCProperty) {
  11422. VK = VK_LValue;
  11423. OK = LHS.get()->getObjectKind();
  11424. }
  11425. if (ConvertHalfVec)
  11426. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  11427. OpLoc, FPFeatures);
  11428. return new (Context) CompoundAssignOperator(
  11429. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  11430. OpLoc, FPFeatures);
  11431. }
  11432. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  11433. /// operators are mixed in a way that suggests that the programmer forgot that
  11434. /// comparison operators have higher precedence. The most typical example of
  11435. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  11436. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  11437. SourceLocation OpLoc, Expr *LHSExpr,
  11438. Expr *RHSExpr) {
  11439. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  11440. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  11441. // Check that one of the sides is a comparison operator and the other isn't.
  11442. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  11443. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  11444. if (isLeftComp == isRightComp)
  11445. return;
  11446. // Bitwise operations are sometimes used as eager logical ops.
  11447. // Don't diagnose this.
  11448. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  11449. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  11450. if (isLeftBitwise || isRightBitwise)
  11451. return;
  11452. SourceRange DiagRange = isLeftComp
  11453. ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
  11454. : SourceRange(OpLoc, RHSExpr->getEndLoc());
  11455. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  11456. SourceRange ParensRange =
  11457. isLeftComp
  11458. ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
  11459. : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
  11460. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  11461. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  11462. SuggestParentheses(Self, OpLoc,
  11463. Self.PDiag(diag::note_precedence_silence) << OpStr,
  11464. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  11465. SuggestParentheses(Self, OpLoc,
  11466. Self.PDiag(diag::note_precedence_bitwise_first)
  11467. << BinaryOperator::getOpcodeStr(Opc),
  11468. ParensRange);
  11469. }
  11470. /// It accepts a '&&' expr that is inside a '||' one.
  11471. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  11472. /// in parentheses.
  11473. static void
  11474. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  11475. BinaryOperator *Bop) {
  11476. assert(Bop->getOpcode() == BO_LAnd);
  11477. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  11478. << Bop->getSourceRange() << OpLoc;
  11479. SuggestParentheses(Self, Bop->getOperatorLoc(),
  11480. Self.PDiag(diag::note_precedence_silence)
  11481. << Bop->getOpcodeStr(),
  11482. Bop->getSourceRange());
  11483. }
  11484. /// Returns true if the given expression can be evaluated as a constant
  11485. /// 'true'.
  11486. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  11487. bool Res;
  11488. return !E->isValueDependent() &&
  11489. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  11490. }
  11491. /// Returns true if the given expression can be evaluated as a constant
  11492. /// 'false'.
  11493. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  11494. bool Res;
  11495. return !E->isValueDependent() &&
  11496. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  11497. }
  11498. /// Look for '&&' in the left hand of a '||' expr.
  11499. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  11500. Expr *LHSExpr, Expr *RHSExpr) {
  11501. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  11502. if (Bop->getOpcode() == BO_LAnd) {
  11503. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  11504. if (EvaluatesAsFalse(S, RHSExpr))
  11505. return;
  11506. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  11507. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  11508. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11509. } else if (Bop->getOpcode() == BO_LOr) {
  11510. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  11511. // If it's "a || b && 1 || c" we didn't warn earlier for
  11512. // "a || b && 1", but warn now.
  11513. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  11514. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  11515. }
  11516. }
  11517. }
  11518. }
  11519. /// Look for '&&' in the right hand of a '||' expr.
  11520. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  11521. Expr *LHSExpr, Expr *RHSExpr) {
  11522. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  11523. if (Bop->getOpcode() == BO_LAnd) {
  11524. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  11525. if (EvaluatesAsFalse(S, LHSExpr))
  11526. return;
  11527. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  11528. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  11529. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  11530. }
  11531. }
  11532. }
  11533. /// Look for bitwise op in the left or right hand of a bitwise op with
  11534. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  11535. /// the '&' expression in parentheses.
  11536. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  11537. SourceLocation OpLoc, Expr *SubExpr) {
  11538. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11539. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  11540. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  11541. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  11542. << Bop->getSourceRange() << OpLoc;
  11543. SuggestParentheses(S, Bop->getOperatorLoc(),
  11544. S.PDiag(diag::note_precedence_silence)
  11545. << Bop->getOpcodeStr(),
  11546. Bop->getSourceRange());
  11547. }
  11548. }
  11549. }
  11550. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  11551. Expr *SubExpr, StringRef Shift) {
  11552. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  11553. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  11554. StringRef Op = Bop->getOpcodeStr();
  11555. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  11556. << Bop->getSourceRange() << OpLoc << Shift << Op;
  11557. SuggestParentheses(S, Bop->getOperatorLoc(),
  11558. S.PDiag(diag::note_precedence_silence) << Op,
  11559. Bop->getSourceRange());
  11560. }
  11561. }
  11562. }
  11563. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  11564. Expr *LHSExpr, Expr *RHSExpr) {
  11565. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  11566. if (!OCE)
  11567. return;
  11568. FunctionDecl *FD = OCE->getDirectCallee();
  11569. if (!FD || !FD->isOverloadedOperator())
  11570. return;
  11571. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  11572. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  11573. return;
  11574. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  11575. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  11576. << (Kind == OO_LessLess);
  11577. SuggestParentheses(S, OCE->getOperatorLoc(),
  11578. S.PDiag(diag::note_precedence_silence)
  11579. << (Kind == OO_LessLess ? "<<" : ">>"),
  11580. OCE->getSourceRange());
  11581. SuggestParentheses(
  11582. S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
  11583. SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
  11584. }
  11585. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  11586. /// precedence.
  11587. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  11588. SourceLocation OpLoc, Expr *LHSExpr,
  11589. Expr *RHSExpr){
  11590. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  11591. if (BinaryOperator::isBitwiseOp(Opc))
  11592. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  11593. // Diagnose "arg1 & arg2 | arg3"
  11594. if ((Opc == BO_Or || Opc == BO_Xor) &&
  11595. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11596. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  11597. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  11598. }
  11599. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  11600. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  11601. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  11602. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  11603. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  11604. }
  11605. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  11606. || Opc == BO_Shr) {
  11607. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  11608. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  11609. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  11610. }
  11611. // Warn on overloaded shift operators and comparisons, such as:
  11612. // cout << 5 == 4;
  11613. if (BinaryOperator::isComparisonOp(Opc))
  11614. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  11615. }
  11616. // Binary Operators. 'Tok' is the token for the operator.
  11617. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  11618. tok::TokenKind Kind,
  11619. Expr *LHSExpr, Expr *RHSExpr) {
  11620. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  11621. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  11622. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  11623. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  11624. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  11625. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  11626. }
  11627. /// Build an overloaded binary operator expression in the given scope.
  11628. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  11629. BinaryOperatorKind Opc,
  11630. Expr *LHS, Expr *RHS) {
  11631. switch (Opc) {
  11632. case BO_Assign:
  11633. case BO_DivAssign:
  11634. case BO_RemAssign:
  11635. case BO_SubAssign:
  11636. case BO_AndAssign:
  11637. case BO_OrAssign:
  11638. case BO_XorAssign:
  11639. DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
  11640. CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
  11641. break;
  11642. default:
  11643. break;
  11644. }
  11645. // Find all of the overloaded operators visible from this
  11646. // point. We perform both an operator-name lookup from the local
  11647. // scope and an argument-dependent lookup based on the types of
  11648. // the arguments.
  11649. UnresolvedSet<16> Functions;
  11650. OverloadedOperatorKind OverOp
  11651. = BinaryOperator::getOverloadedOperator(Opc);
  11652. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  11653. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  11654. RHS->getType(), Functions);
  11655. // Build the (potentially-overloaded, potentially-dependent)
  11656. // binary operation.
  11657. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  11658. }
  11659. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  11660. BinaryOperatorKind Opc,
  11661. Expr *LHSExpr, Expr *RHSExpr) {
  11662. ExprResult LHS, RHS;
  11663. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  11664. if (!LHS.isUsable() || !RHS.isUsable())
  11665. return ExprError();
  11666. LHSExpr = LHS.get();
  11667. RHSExpr = RHS.get();
  11668. // We want to end up calling one of checkPseudoObjectAssignment
  11669. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  11670. // both expressions are overloadable or either is type-dependent),
  11671. // or CreateBuiltinBinOp (in any other case). We also want to get
  11672. // any placeholder types out of the way.
  11673. // Handle pseudo-objects in the LHS.
  11674. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  11675. // Assignments with a pseudo-object l-value need special analysis.
  11676. if (pty->getKind() == BuiltinType::PseudoObject &&
  11677. BinaryOperator::isAssignmentOp(Opc))
  11678. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  11679. // Don't resolve overloads if the other type is overloadable.
  11680. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  11681. // We can't actually test that if we still have a placeholder,
  11682. // though. Fortunately, none of the exceptions we see in that
  11683. // code below are valid when the LHS is an overload set. Note
  11684. // that an overload set can be dependently-typed, but it never
  11685. // instantiates to having an overloadable type.
  11686. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11687. if (resolvedRHS.isInvalid()) return ExprError();
  11688. RHSExpr = resolvedRHS.get();
  11689. if (RHSExpr->isTypeDependent() ||
  11690. RHSExpr->getType()->isOverloadableType())
  11691. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11692. }
  11693. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  11694. // template, diagnose the missing 'template' keyword instead of diagnosing
  11695. // an invalid use of a bound member function.
  11696. //
  11697. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  11698. // to C++1z [over.over]/1.4, but we already checked for that case above.
  11699. if (Opc == BO_LT && inTemplateInstantiation() &&
  11700. (pty->getKind() == BuiltinType::BoundMember ||
  11701. pty->getKind() == BuiltinType::Overload)) {
  11702. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  11703. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  11704. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  11705. return isa<FunctionTemplateDecl>(ND);
  11706. })) {
  11707. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  11708. : OE->getNameLoc(),
  11709. diag::err_template_kw_missing)
  11710. << OE->getName().getAsString() << "";
  11711. return ExprError();
  11712. }
  11713. }
  11714. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  11715. if (LHS.isInvalid()) return ExprError();
  11716. LHSExpr = LHS.get();
  11717. }
  11718. // Handle pseudo-objects in the RHS.
  11719. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  11720. // An overload in the RHS can potentially be resolved by the type
  11721. // being assigned to.
  11722. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  11723. if (getLangOpts().CPlusPlus &&
  11724. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  11725. LHSExpr->getType()->isOverloadableType()))
  11726. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11727. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11728. }
  11729. // Don't resolve overloads if the other type is overloadable.
  11730. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  11731. LHSExpr->getType()->isOverloadableType())
  11732. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11733. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  11734. if (!resolvedRHS.isUsable()) return ExprError();
  11735. RHSExpr = resolvedRHS.get();
  11736. }
  11737. if (getLangOpts().CPlusPlus) {
  11738. // If either expression is type-dependent, always build an
  11739. // overloaded op.
  11740. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  11741. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11742. // Otherwise, build an overloaded op if either expression has an
  11743. // overloadable type.
  11744. if (LHSExpr->getType()->isOverloadableType() ||
  11745. RHSExpr->getType()->isOverloadableType())
  11746. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  11747. }
  11748. // Build a built-in binary operation.
  11749. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  11750. }
  11751. static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
  11752. if (T.isNull() || T->isDependentType())
  11753. return false;
  11754. if (!T->isPromotableIntegerType())
  11755. return true;
  11756. return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
  11757. }
  11758. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  11759. UnaryOperatorKind Opc,
  11760. Expr *InputExpr) {
  11761. ExprResult Input = InputExpr;
  11762. ExprValueKind VK = VK_RValue;
  11763. ExprObjectKind OK = OK_Ordinary;
  11764. QualType resultType;
  11765. bool CanOverflow = false;
  11766. bool ConvertHalfVec = false;
  11767. if (getLangOpts().OpenCL) {
  11768. QualType Ty = InputExpr->getType();
  11769. // The only legal unary operation for atomics is '&'.
  11770. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  11771. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  11772. // only with a builtin functions and therefore should be disallowed here.
  11773. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  11774. || Ty->isBlockPointerType())) {
  11775. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11776. << InputExpr->getType()
  11777. << Input.get()->getSourceRange());
  11778. }
  11779. }
  11780. // Diagnose operations on the unsupported types for OpenMP device compilation.
  11781. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
  11782. if (UnaryOperator::isIncrementDecrementOp(Opc) ||
  11783. UnaryOperator::isArithmeticOp(Opc))
  11784. checkOpenMPDeviceExpr(InputExpr);
  11785. }
  11786. switch (Opc) {
  11787. case UO_PreInc:
  11788. case UO_PreDec:
  11789. case UO_PostInc:
  11790. case UO_PostDec:
  11791. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  11792. OpLoc,
  11793. Opc == UO_PreInc ||
  11794. Opc == UO_PostInc,
  11795. Opc == UO_PreInc ||
  11796. Opc == UO_PreDec);
  11797. CanOverflow = isOverflowingIntegerType(Context, resultType);
  11798. break;
  11799. case UO_AddrOf:
  11800. resultType = CheckAddressOfOperand(Input, OpLoc);
  11801. CheckAddressOfNoDeref(InputExpr);
  11802. RecordModifiableNonNullParam(*this, InputExpr);
  11803. break;
  11804. case UO_Deref: {
  11805. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11806. if (Input.isInvalid()) return ExprError();
  11807. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  11808. break;
  11809. }
  11810. case UO_Plus:
  11811. case UO_Minus:
  11812. CanOverflow = Opc == UO_Minus &&
  11813. isOverflowingIntegerType(Context, Input.get()->getType());
  11814. Input = UsualUnaryConversions(Input.get());
  11815. if (Input.isInvalid()) return ExprError();
  11816. // Unary plus and minus require promoting an operand of half vector to a
  11817. // float vector and truncating the result back to a half vector. For now, we
  11818. // do this only when HalfArgsAndReturns is set (that is, when the target is
  11819. // arm or arm64).
  11820. ConvertHalfVec =
  11821. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  11822. // If the operand is a half vector, promote it to a float vector.
  11823. if (ConvertHalfVec)
  11824. Input = convertVector(Input.get(), Context.FloatTy, *this);
  11825. resultType = Input.get()->getType();
  11826. if (resultType->isDependentType())
  11827. break;
  11828. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  11829. break;
  11830. else if (resultType->isVectorType() &&
  11831. // The z vector extensions don't allow + or - with bool vectors.
  11832. (!Context.getLangOpts().ZVector ||
  11833. resultType->getAs<VectorType>()->getVectorKind() !=
  11834. VectorType::AltiVecBool))
  11835. break;
  11836. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  11837. Opc == UO_Plus &&
  11838. resultType->isPointerType())
  11839. break;
  11840. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11841. << resultType << Input.get()->getSourceRange());
  11842. case UO_Not: // bitwise complement
  11843. Input = UsualUnaryConversions(Input.get());
  11844. if (Input.isInvalid())
  11845. return ExprError();
  11846. resultType = Input.get()->getType();
  11847. if (resultType->isDependentType())
  11848. break;
  11849. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  11850. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  11851. // C99 does not support '~' for complex conjugation.
  11852. Diag(OpLoc, diag::ext_integer_complement_complex)
  11853. << resultType << Input.get()->getSourceRange();
  11854. else if (resultType->hasIntegerRepresentation())
  11855. break;
  11856. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  11857. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  11858. // on vector float types.
  11859. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11860. if (!T->isIntegerType())
  11861. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11862. << resultType << Input.get()->getSourceRange());
  11863. } else {
  11864. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11865. << resultType << Input.get()->getSourceRange());
  11866. }
  11867. break;
  11868. case UO_LNot: // logical negation
  11869. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  11870. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  11871. if (Input.isInvalid()) return ExprError();
  11872. resultType = Input.get()->getType();
  11873. // Though we still have to promote half FP to float...
  11874. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  11875. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  11876. resultType = Context.FloatTy;
  11877. }
  11878. if (resultType->isDependentType())
  11879. break;
  11880. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  11881. // C99 6.5.3.3p1: ok, fallthrough;
  11882. if (Context.getLangOpts().CPlusPlus) {
  11883. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  11884. // operand contextually converted to bool.
  11885. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  11886. ScalarTypeToBooleanCastKind(resultType));
  11887. } else if (Context.getLangOpts().OpenCL &&
  11888. Context.getLangOpts().OpenCLVersion < 120) {
  11889. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11890. // operate on scalar float types.
  11891. if (!resultType->isIntegerType() && !resultType->isPointerType())
  11892. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11893. << resultType << Input.get()->getSourceRange());
  11894. }
  11895. } else if (resultType->isExtVectorType()) {
  11896. if (Context.getLangOpts().OpenCL &&
  11897. Context.getLangOpts().OpenCLVersion < 120 &&
  11898. !Context.getLangOpts().OpenCLCPlusPlus) {
  11899. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  11900. // operate on vector float types.
  11901. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  11902. if (!T->isIntegerType())
  11903. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11904. << resultType << Input.get()->getSourceRange());
  11905. }
  11906. // Vector logical not returns the signed variant of the operand type.
  11907. resultType = GetSignedVectorType(resultType);
  11908. break;
  11909. } else {
  11910. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  11911. // type in C++. We should allow that here too.
  11912. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  11913. << resultType << Input.get()->getSourceRange());
  11914. }
  11915. // LNot always has type int. C99 6.5.3.3p5.
  11916. // In C++, it's bool. C++ 5.3.1p8
  11917. resultType = Context.getLogicalOperationType();
  11918. break;
  11919. case UO_Real:
  11920. case UO_Imag:
  11921. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  11922. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  11923. // complex l-values to ordinary l-values and all other values to r-values.
  11924. if (Input.isInvalid()) return ExprError();
  11925. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  11926. if (Input.get()->getValueKind() != VK_RValue &&
  11927. Input.get()->getObjectKind() == OK_Ordinary)
  11928. VK = Input.get()->getValueKind();
  11929. } else if (!getLangOpts().CPlusPlus) {
  11930. // In C, a volatile scalar is read by __imag. In C++, it is not.
  11931. Input = DefaultLvalueConversion(Input.get());
  11932. }
  11933. break;
  11934. case UO_Extension:
  11935. resultType = Input.get()->getType();
  11936. VK = Input.get()->getValueKind();
  11937. OK = Input.get()->getObjectKind();
  11938. break;
  11939. case UO_Coawait:
  11940. // It's unnecessary to represent the pass-through operator co_await in the
  11941. // AST; just return the input expression instead.
  11942. assert(!Input.get()->getType()->isDependentType() &&
  11943. "the co_await expression must be non-dependant before "
  11944. "building operator co_await");
  11945. return Input;
  11946. }
  11947. if (resultType.isNull() || Input.isInvalid())
  11948. return ExprError();
  11949. // Check for array bounds violations in the operand of the UnaryOperator,
  11950. // except for the '*' and '&' operators that have to be handled specially
  11951. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  11952. // that are explicitly defined as valid by the standard).
  11953. if (Opc != UO_AddrOf && Opc != UO_Deref)
  11954. CheckArrayAccess(Input.get());
  11955. auto *UO = new (Context)
  11956. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
  11957. if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
  11958. !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
  11959. ExprEvalContexts.back().PossibleDerefs.insert(UO);
  11960. // Convert the result back to a half vector.
  11961. if (ConvertHalfVec)
  11962. return convertVector(UO, Context.HalfTy, *this);
  11963. return UO;
  11964. }
  11965. /// Determine whether the given expression is a qualified member
  11966. /// access expression, of a form that could be turned into a pointer to member
  11967. /// with the address-of operator.
  11968. bool Sema::isQualifiedMemberAccess(Expr *E) {
  11969. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  11970. if (!DRE->getQualifier())
  11971. return false;
  11972. ValueDecl *VD = DRE->getDecl();
  11973. if (!VD->isCXXClassMember())
  11974. return false;
  11975. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  11976. return true;
  11977. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  11978. return Method->isInstance();
  11979. return false;
  11980. }
  11981. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  11982. if (!ULE->getQualifier())
  11983. return false;
  11984. for (NamedDecl *D : ULE->decls()) {
  11985. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  11986. if (Method->isInstance())
  11987. return true;
  11988. } else {
  11989. // Overload set does not contain methods.
  11990. break;
  11991. }
  11992. }
  11993. return false;
  11994. }
  11995. return false;
  11996. }
  11997. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  11998. UnaryOperatorKind Opc, Expr *Input) {
  11999. // First things first: handle placeholders so that the
  12000. // overloaded-operator check considers the right type.
  12001. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  12002. // Increment and decrement of pseudo-object references.
  12003. if (pty->getKind() == BuiltinType::PseudoObject &&
  12004. UnaryOperator::isIncrementDecrementOp(Opc))
  12005. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  12006. // extension is always a builtin operator.
  12007. if (Opc == UO_Extension)
  12008. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12009. // & gets special logic for several kinds of placeholder.
  12010. // The builtin code knows what to do.
  12011. if (Opc == UO_AddrOf &&
  12012. (pty->getKind() == BuiltinType::Overload ||
  12013. pty->getKind() == BuiltinType::UnknownAny ||
  12014. pty->getKind() == BuiltinType::BoundMember))
  12015. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12016. // Anything else needs to be handled now.
  12017. ExprResult Result = CheckPlaceholderExpr(Input);
  12018. if (Result.isInvalid()) return ExprError();
  12019. Input = Result.get();
  12020. }
  12021. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  12022. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  12023. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  12024. // Find all of the overloaded operators visible from this
  12025. // point. We perform both an operator-name lookup from the local
  12026. // scope and an argument-dependent lookup based on the types of
  12027. // the arguments.
  12028. UnresolvedSet<16> Functions;
  12029. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  12030. if (S && OverOp != OO_None)
  12031. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  12032. Functions);
  12033. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  12034. }
  12035. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  12036. }
  12037. // Unary Operators. 'Tok' is the token for the operator.
  12038. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  12039. tok::TokenKind Op, Expr *Input) {
  12040. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  12041. }
  12042. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  12043. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  12044. LabelDecl *TheDecl) {
  12045. TheDecl->markUsed(Context);
  12046. // Create the AST node. The address of a label always has type 'void*'.
  12047. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  12048. Context.getPointerType(Context.VoidTy));
  12049. }
  12050. void Sema::ActOnStartStmtExpr() {
  12051. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  12052. }
  12053. void Sema::ActOnStmtExprError() {
  12054. // Note that function is also called by TreeTransform when leaving a
  12055. // StmtExpr scope without rebuilding anything.
  12056. DiscardCleanupsInEvaluationContext();
  12057. PopExpressionEvaluationContext();
  12058. }
  12059. ExprResult
  12060. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  12061. SourceLocation RPLoc) { // "({..})"
  12062. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  12063. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  12064. if (hasAnyUnrecoverableErrorsInThisFunction())
  12065. DiscardCleanupsInEvaluationContext();
  12066. assert(!Cleanup.exprNeedsCleanups() &&
  12067. "cleanups within StmtExpr not correctly bound!");
  12068. PopExpressionEvaluationContext();
  12069. // FIXME: there are a variety of strange constraints to enforce here, for
  12070. // example, it is not possible to goto into a stmt expression apparently.
  12071. // More semantic analysis is needed.
  12072. // If there are sub-stmts in the compound stmt, take the type of the last one
  12073. // as the type of the stmtexpr.
  12074. QualType Ty = Context.VoidTy;
  12075. bool StmtExprMayBindToTemp = false;
  12076. if (!Compound->body_empty()) {
  12077. // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
  12078. if (const auto *LastStmt =
  12079. dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
  12080. if (const Expr *Value = LastStmt->getExprStmt()) {
  12081. StmtExprMayBindToTemp = true;
  12082. Ty = Value->getType();
  12083. }
  12084. }
  12085. }
  12086. // FIXME: Check that expression type is complete/non-abstract; statement
  12087. // expressions are not lvalues.
  12088. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  12089. if (StmtExprMayBindToTemp)
  12090. return MaybeBindToTemporary(ResStmtExpr);
  12091. return ResStmtExpr;
  12092. }
  12093. ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
  12094. if (ER.isInvalid())
  12095. return ExprError();
  12096. // Do function/array conversion on the last expression, but not
  12097. // lvalue-to-rvalue. However, initialize an unqualified type.
  12098. ER = DefaultFunctionArrayConversion(ER.get());
  12099. if (ER.isInvalid())
  12100. return ExprError();
  12101. Expr *E = ER.get();
  12102. if (E->isTypeDependent())
  12103. return E;
  12104. // In ARC, if the final expression ends in a consume, splice
  12105. // the consume out and bind it later. In the alternate case
  12106. // (when dealing with a retainable type), the result
  12107. // initialization will create a produce. In both cases the
  12108. // result will be +1, and we'll need to balance that out with
  12109. // a bind.
  12110. auto *Cast = dyn_cast<ImplicitCastExpr>(E);
  12111. if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
  12112. return Cast->getSubExpr();
  12113. // FIXME: Provide a better location for the initialization.
  12114. return PerformCopyInitialization(
  12115. InitializedEntity::InitializeStmtExprResult(
  12116. E->getBeginLoc(), E->getType().getUnqualifiedType()),
  12117. SourceLocation(), E);
  12118. }
  12119. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  12120. TypeSourceInfo *TInfo,
  12121. ArrayRef<OffsetOfComponent> Components,
  12122. SourceLocation RParenLoc) {
  12123. QualType ArgTy = TInfo->getType();
  12124. bool Dependent = ArgTy->isDependentType();
  12125. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  12126. // We must have at least one component that refers to the type, and the first
  12127. // one is known to be a field designator. Verify that the ArgTy represents
  12128. // a struct/union/class.
  12129. if (!Dependent && !ArgTy->isRecordType())
  12130. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  12131. << ArgTy << TypeRange);
  12132. // Type must be complete per C99 7.17p3 because a declaring a variable
  12133. // with an incomplete type would be ill-formed.
  12134. if (!Dependent
  12135. && RequireCompleteType(BuiltinLoc, ArgTy,
  12136. diag::err_offsetof_incomplete_type, TypeRange))
  12137. return ExprError();
  12138. bool DidWarnAboutNonPOD = false;
  12139. QualType CurrentType = ArgTy;
  12140. SmallVector<OffsetOfNode, 4> Comps;
  12141. SmallVector<Expr*, 4> Exprs;
  12142. for (const OffsetOfComponent &OC : Components) {
  12143. if (OC.isBrackets) {
  12144. // Offset of an array sub-field. TODO: Should we allow vector elements?
  12145. if (!CurrentType->isDependentType()) {
  12146. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  12147. if(!AT)
  12148. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  12149. << CurrentType);
  12150. CurrentType = AT->getElementType();
  12151. } else
  12152. CurrentType = Context.DependentTy;
  12153. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  12154. if (IdxRval.isInvalid())
  12155. return ExprError();
  12156. Expr *Idx = IdxRval.get();
  12157. // The expression must be an integral expression.
  12158. // FIXME: An integral constant expression?
  12159. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  12160. !Idx->getType()->isIntegerType())
  12161. return ExprError(
  12162. Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
  12163. << Idx->getSourceRange());
  12164. // Record this array index.
  12165. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  12166. Exprs.push_back(Idx);
  12167. continue;
  12168. }
  12169. // Offset of a field.
  12170. if (CurrentType->isDependentType()) {
  12171. // We have the offset of a field, but we can't look into the dependent
  12172. // type. Just record the identifier of the field.
  12173. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  12174. CurrentType = Context.DependentTy;
  12175. continue;
  12176. }
  12177. // We need to have a complete type to look into.
  12178. if (RequireCompleteType(OC.LocStart, CurrentType,
  12179. diag::err_offsetof_incomplete_type))
  12180. return ExprError();
  12181. // Look for the designated field.
  12182. const RecordType *RC = CurrentType->getAs<RecordType>();
  12183. if (!RC)
  12184. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  12185. << CurrentType);
  12186. RecordDecl *RD = RC->getDecl();
  12187. // C++ [lib.support.types]p5:
  12188. // The macro offsetof accepts a restricted set of type arguments in this
  12189. // International Standard. type shall be a POD structure or a POD union
  12190. // (clause 9).
  12191. // C++11 [support.types]p4:
  12192. // If type is not a standard-layout class (Clause 9), the results are
  12193. // undefined.
  12194. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  12195. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  12196. unsigned DiagID =
  12197. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  12198. : diag::ext_offsetof_non_pod_type;
  12199. if (!IsSafe && !DidWarnAboutNonPOD &&
  12200. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  12201. PDiag(DiagID)
  12202. << SourceRange(Components[0].LocStart, OC.LocEnd)
  12203. << CurrentType))
  12204. DidWarnAboutNonPOD = true;
  12205. }
  12206. // Look for the field.
  12207. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  12208. LookupQualifiedName(R, RD);
  12209. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  12210. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  12211. if (!MemberDecl) {
  12212. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  12213. MemberDecl = IndirectMemberDecl->getAnonField();
  12214. }
  12215. if (!MemberDecl)
  12216. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  12217. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  12218. OC.LocEnd));
  12219. // C99 7.17p3:
  12220. // (If the specified member is a bit-field, the behavior is undefined.)
  12221. //
  12222. // We diagnose this as an error.
  12223. if (MemberDecl->isBitField()) {
  12224. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  12225. << MemberDecl->getDeclName()
  12226. << SourceRange(BuiltinLoc, RParenLoc);
  12227. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  12228. return ExprError();
  12229. }
  12230. RecordDecl *Parent = MemberDecl->getParent();
  12231. if (IndirectMemberDecl)
  12232. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  12233. // If the member was found in a base class, introduce OffsetOfNodes for
  12234. // the base class indirections.
  12235. CXXBasePaths Paths;
  12236. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  12237. Paths)) {
  12238. if (Paths.getDetectedVirtual()) {
  12239. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  12240. << MemberDecl->getDeclName()
  12241. << SourceRange(BuiltinLoc, RParenLoc);
  12242. return ExprError();
  12243. }
  12244. CXXBasePath &Path = Paths.front();
  12245. for (const CXXBasePathElement &B : Path)
  12246. Comps.push_back(OffsetOfNode(B.Base));
  12247. }
  12248. if (IndirectMemberDecl) {
  12249. for (auto *FI : IndirectMemberDecl->chain()) {
  12250. assert(isa<FieldDecl>(FI));
  12251. Comps.push_back(OffsetOfNode(OC.LocStart,
  12252. cast<FieldDecl>(FI), OC.LocEnd));
  12253. }
  12254. } else
  12255. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  12256. CurrentType = MemberDecl->getType().getNonReferenceType();
  12257. }
  12258. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  12259. Comps, Exprs, RParenLoc);
  12260. }
  12261. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  12262. SourceLocation BuiltinLoc,
  12263. SourceLocation TypeLoc,
  12264. ParsedType ParsedArgTy,
  12265. ArrayRef<OffsetOfComponent> Components,
  12266. SourceLocation RParenLoc) {
  12267. TypeSourceInfo *ArgTInfo;
  12268. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  12269. if (ArgTy.isNull())
  12270. return ExprError();
  12271. if (!ArgTInfo)
  12272. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  12273. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  12274. }
  12275. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  12276. Expr *CondExpr,
  12277. Expr *LHSExpr, Expr *RHSExpr,
  12278. SourceLocation RPLoc) {
  12279. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  12280. ExprValueKind VK = VK_RValue;
  12281. ExprObjectKind OK = OK_Ordinary;
  12282. QualType resType;
  12283. bool ValueDependent = false;
  12284. bool CondIsTrue = false;
  12285. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  12286. resType = Context.DependentTy;
  12287. ValueDependent = true;
  12288. } else {
  12289. // The conditional expression is required to be a constant expression.
  12290. llvm::APSInt condEval(32);
  12291. ExprResult CondICE
  12292. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  12293. diag::err_typecheck_choose_expr_requires_constant, false);
  12294. if (CondICE.isInvalid())
  12295. return ExprError();
  12296. CondExpr = CondICE.get();
  12297. CondIsTrue = condEval.getZExtValue();
  12298. // If the condition is > zero, then the AST type is the same as the LHSExpr.
  12299. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  12300. resType = ActiveExpr->getType();
  12301. ValueDependent = ActiveExpr->isValueDependent();
  12302. VK = ActiveExpr->getValueKind();
  12303. OK = ActiveExpr->getObjectKind();
  12304. }
  12305. return new (Context)
  12306. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  12307. CondIsTrue, resType->isDependentType(), ValueDependent);
  12308. }
  12309. //===----------------------------------------------------------------------===//
  12310. // Clang Extensions.
  12311. //===----------------------------------------------------------------------===//
  12312. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  12313. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  12314. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  12315. if (LangOpts.CPlusPlus) {
  12316. Decl *ManglingContextDecl;
  12317. if (MangleNumberingContext *MCtx =
  12318. getCurrentMangleNumberContext(Block->getDeclContext(),
  12319. ManglingContextDecl)) {
  12320. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  12321. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  12322. }
  12323. }
  12324. PushBlockScope(CurScope, Block);
  12325. CurContext->addDecl(Block);
  12326. if (CurScope)
  12327. PushDeclContext(CurScope, Block);
  12328. else
  12329. CurContext = Block;
  12330. getCurBlock()->HasImplicitReturnType = true;
  12331. // Enter a new evaluation context to insulate the block from any
  12332. // cleanups from the enclosing full-expression.
  12333. PushExpressionEvaluationContext(
  12334. ExpressionEvaluationContext::PotentiallyEvaluated);
  12335. }
  12336. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  12337. Scope *CurScope) {
  12338. assert(ParamInfo.getIdentifier() == nullptr &&
  12339. "block-id should have no identifier!");
  12340. assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
  12341. BlockScopeInfo *CurBlock = getCurBlock();
  12342. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  12343. QualType T = Sig->getType();
  12344. // FIXME: We should allow unexpanded parameter packs here, but that would,
  12345. // in turn, make the block expression contain unexpanded parameter packs.
  12346. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  12347. // Drop the parameters.
  12348. FunctionProtoType::ExtProtoInfo EPI;
  12349. EPI.HasTrailingReturn = false;
  12350. EPI.TypeQuals.addConst();
  12351. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  12352. Sig = Context.getTrivialTypeSourceInfo(T);
  12353. }
  12354. // GetTypeForDeclarator always produces a function type for a block
  12355. // literal signature. Furthermore, it is always a FunctionProtoType
  12356. // unless the function was written with a typedef.
  12357. assert(T->isFunctionType() &&
  12358. "GetTypeForDeclarator made a non-function block signature");
  12359. // Look for an explicit signature in that function type.
  12360. FunctionProtoTypeLoc ExplicitSignature;
  12361. if ((ExplicitSignature = Sig->getTypeLoc()
  12362. .getAsAdjusted<FunctionProtoTypeLoc>())) {
  12363. // Check whether that explicit signature was synthesized by
  12364. // GetTypeForDeclarator. If so, don't save that as part of the
  12365. // written signature.
  12366. if (ExplicitSignature.getLocalRangeBegin() ==
  12367. ExplicitSignature.getLocalRangeEnd()) {
  12368. // This would be much cheaper if we stored TypeLocs instead of
  12369. // TypeSourceInfos.
  12370. TypeLoc Result = ExplicitSignature.getReturnLoc();
  12371. unsigned Size = Result.getFullDataSize();
  12372. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  12373. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  12374. ExplicitSignature = FunctionProtoTypeLoc();
  12375. }
  12376. }
  12377. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  12378. CurBlock->FunctionType = T;
  12379. const FunctionType *Fn = T->getAs<FunctionType>();
  12380. QualType RetTy = Fn->getReturnType();
  12381. bool isVariadic =
  12382. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  12383. CurBlock->TheDecl->setIsVariadic(isVariadic);
  12384. // Context.DependentTy is used as a placeholder for a missing block
  12385. // return type. TODO: what should we do with declarators like:
  12386. // ^ * { ... }
  12387. // If the answer is "apply template argument deduction"....
  12388. if (RetTy != Context.DependentTy) {
  12389. CurBlock->ReturnType = RetTy;
  12390. CurBlock->TheDecl->setBlockMissingReturnType(false);
  12391. CurBlock->HasImplicitReturnType = false;
  12392. }
  12393. // Push block parameters from the declarator if we had them.
  12394. SmallVector<ParmVarDecl*, 8> Params;
  12395. if (ExplicitSignature) {
  12396. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  12397. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  12398. if (Param->getIdentifier() == nullptr &&
  12399. !Param->isImplicit() &&
  12400. !Param->isInvalidDecl() &&
  12401. !getLangOpts().CPlusPlus)
  12402. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  12403. Params.push_back(Param);
  12404. }
  12405. // Fake up parameter variables if we have a typedef, like
  12406. // ^ fntype { ... }
  12407. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  12408. for (const auto &I : Fn->param_types()) {
  12409. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  12410. CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
  12411. Params.push_back(Param);
  12412. }
  12413. }
  12414. // Set the parameters on the block decl.
  12415. if (!Params.empty()) {
  12416. CurBlock->TheDecl->setParams(Params);
  12417. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  12418. /*CheckParameterNames=*/false);
  12419. }
  12420. // Finally we can process decl attributes.
  12421. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  12422. // Put the parameter variables in scope.
  12423. for (auto AI : CurBlock->TheDecl->parameters()) {
  12424. AI->setOwningFunction(CurBlock->TheDecl);
  12425. // If this has an identifier, add it to the scope stack.
  12426. if (AI->getIdentifier()) {
  12427. CheckShadow(CurBlock->TheScope, AI);
  12428. PushOnScopeChains(AI, CurBlock->TheScope);
  12429. }
  12430. }
  12431. }
  12432. /// ActOnBlockError - If there is an error parsing a block, this callback
  12433. /// is invoked to pop the information about the block from the action impl.
  12434. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  12435. // Leave the expression-evaluation context.
  12436. DiscardCleanupsInEvaluationContext();
  12437. PopExpressionEvaluationContext();
  12438. // Pop off CurBlock, handle nested blocks.
  12439. PopDeclContext();
  12440. PopFunctionScopeInfo();
  12441. }
  12442. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  12443. /// literal was successfully completed. ^(int x){...}
  12444. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  12445. Stmt *Body, Scope *CurScope) {
  12446. // If blocks are disabled, emit an error.
  12447. if (!LangOpts.Blocks)
  12448. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  12449. // Leave the expression-evaluation context.
  12450. if (hasAnyUnrecoverableErrorsInThisFunction())
  12451. DiscardCleanupsInEvaluationContext();
  12452. assert(!Cleanup.exprNeedsCleanups() &&
  12453. "cleanups within block not correctly bound!");
  12454. PopExpressionEvaluationContext();
  12455. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  12456. BlockDecl *BD = BSI->TheDecl;
  12457. if (BSI->HasImplicitReturnType)
  12458. deduceClosureReturnType(*BSI);
  12459. QualType RetTy = Context.VoidTy;
  12460. if (!BSI->ReturnType.isNull())
  12461. RetTy = BSI->ReturnType;
  12462. bool NoReturn = BD->hasAttr<NoReturnAttr>();
  12463. QualType BlockTy;
  12464. // If the user wrote a function type in some form, try to use that.
  12465. if (!BSI->FunctionType.isNull()) {
  12466. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  12467. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  12468. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  12469. // Turn protoless block types into nullary block types.
  12470. if (isa<FunctionNoProtoType>(FTy)) {
  12471. FunctionProtoType::ExtProtoInfo EPI;
  12472. EPI.ExtInfo = Ext;
  12473. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12474. // Otherwise, if we don't need to change anything about the function type,
  12475. // preserve its sugar structure.
  12476. } else if (FTy->getReturnType() == RetTy &&
  12477. (!NoReturn || FTy->getNoReturnAttr())) {
  12478. BlockTy = BSI->FunctionType;
  12479. // Otherwise, make the minimal modifications to the function type.
  12480. } else {
  12481. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  12482. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  12483. EPI.TypeQuals = Qualifiers();
  12484. EPI.ExtInfo = Ext;
  12485. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  12486. }
  12487. // If we don't have a function type, just build one from nothing.
  12488. } else {
  12489. FunctionProtoType::ExtProtoInfo EPI;
  12490. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  12491. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  12492. }
  12493. DiagnoseUnusedParameters(BD->parameters());
  12494. BlockTy = Context.getBlockPointerType(BlockTy);
  12495. // If needed, diagnose invalid gotos and switches in the block.
  12496. if (getCurFunction()->NeedsScopeChecking() &&
  12497. !PP.isCodeCompletionEnabled())
  12498. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  12499. BD->setBody(cast<CompoundStmt>(Body));
  12500. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12501. DiagnoseUnguardedAvailabilityViolations(BD);
  12502. // Try to apply the named return value optimization. We have to check again
  12503. // if we can do this, though, because blocks keep return statements around
  12504. // to deduce an implicit return type.
  12505. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  12506. !BD->isDependentContext())
  12507. computeNRVO(Body, BSI);
  12508. PopDeclContext();
  12509. // Pop the block scope now but keep it alive to the end of this function.
  12510. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12511. PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
  12512. // Set the captured variables on the block.
  12513. SmallVector<BlockDecl::Capture, 4> Captures;
  12514. for (Capture &Cap : BSI->Captures) {
  12515. if (Cap.isInvalid() || Cap.isThisCapture())
  12516. continue;
  12517. VarDecl *Var = Cap.getVariable();
  12518. Expr *CopyExpr = nullptr;
  12519. if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
  12520. if (const RecordType *Record =
  12521. Cap.getCaptureType()->getAs<RecordType>()) {
  12522. // The capture logic needs the destructor, so make sure we mark it.
  12523. // Usually this is unnecessary because most local variables have
  12524. // their destructors marked at declaration time, but parameters are
  12525. // an exception because it's technically only the call site that
  12526. // actually requires the destructor.
  12527. if (isa<ParmVarDecl>(Var))
  12528. FinalizeVarWithDestructor(Var, Record);
  12529. // Enter a separate potentially-evaluated context while building block
  12530. // initializers to isolate their cleanups from those of the block
  12531. // itself.
  12532. // FIXME: Is this appropriate even when the block itself occurs in an
  12533. // unevaluated operand?
  12534. EnterExpressionEvaluationContext EvalContext(
  12535. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  12536. SourceLocation Loc = Cap.getLocation();
  12537. ExprResult Result = BuildDeclarationNameExpr(
  12538. CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
  12539. // According to the blocks spec, the capture of a variable from
  12540. // the stack requires a const copy constructor. This is not true
  12541. // of the copy/move done to move a __block variable to the heap.
  12542. if (!Result.isInvalid() &&
  12543. !Result.get()->getType().isConstQualified()) {
  12544. Result = ImpCastExprToType(Result.get(),
  12545. Result.get()->getType().withConst(),
  12546. CK_NoOp, VK_LValue);
  12547. }
  12548. if (!Result.isInvalid()) {
  12549. Result = PerformCopyInitialization(
  12550. InitializedEntity::InitializeBlock(Var->getLocation(),
  12551. Cap.getCaptureType(), false),
  12552. Loc, Result.get());
  12553. }
  12554. // Build a full-expression copy expression if initialization
  12555. // succeeded and used a non-trivial constructor. Recover from
  12556. // errors by pretending that the copy isn't necessary.
  12557. if (!Result.isInvalid() &&
  12558. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12559. ->isTrivial()) {
  12560. Result = MaybeCreateExprWithCleanups(Result);
  12561. CopyExpr = Result.get();
  12562. }
  12563. }
  12564. }
  12565. BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
  12566. CopyExpr);
  12567. Captures.push_back(NewCap);
  12568. }
  12569. BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  12570. BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
  12571. // If the block isn't obviously global, i.e. it captures anything at
  12572. // all, then we need to do a few things in the surrounding context:
  12573. if (Result->getBlockDecl()->hasCaptures()) {
  12574. // First, this expression has a new cleanup object.
  12575. ExprCleanupObjects.push_back(Result->getBlockDecl());
  12576. Cleanup.setExprNeedsCleanups(true);
  12577. // It also gets a branch-protected scope if any of the captured
  12578. // variables needs destruction.
  12579. for (const auto &CI : Result->getBlockDecl()->captures()) {
  12580. const VarDecl *var = CI.getVariable();
  12581. if (var->getType().isDestructedType() != QualType::DK_none) {
  12582. setFunctionHasBranchProtectedScope();
  12583. break;
  12584. }
  12585. }
  12586. }
  12587. if (getCurFunction())
  12588. getCurFunction()->addBlock(BD);
  12589. return Result;
  12590. }
  12591. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  12592. SourceLocation RPLoc) {
  12593. TypeSourceInfo *TInfo;
  12594. GetTypeFromParser(Ty, &TInfo);
  12595. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  12596. }
  12597. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  12598. Expr *E, TypeSourceInfo *TInfo,
  12599. SourceLocation RPLoc) {
  12600. Expr *OrigExpr = E;
  12601. bool IsMS = false;
  12602. // CUDA device code does not support varargs.
  12603. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  12604. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  12605. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  12606. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  12607. return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
  12608. }
  12609. }
  12610. // NVPTX does not support va_arg expression.
  12611. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  12612. Context.getTargetInfo().getTriple().isNVPTX())
  12613. targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
  12614. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  12615. // as Microsoft ABI on an actual Microsoft platform, where
  12616. // __builtin_ms_va_list and __builtin_va_list are the same.)
  12617. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  12618. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  12619. QualType MSVaListType = Context.getBuiltinMSVaListType();
  12620. if (Context.hasSameType(MSVaListType, E->getType())) {
  12621. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12622. return ExprError();
  12623. IsMS = true;
  12624. }
  12625. }
  12626. // Get the va_list type
  12627. QualType VaListType = Context.getBuiltinVaListType();
  12628. if (!IsMS) {
  12629. if (VaListType->isArrayType()) {
  12630. // Deal with implicit array decay; for example, on x86-64,
  12631. // va_list is an array, but it's supposed to decay to
  12632. // a pointer for va_arg.
  12633. VaListType = Context.getArrayDecayedType(VaListType);
  12634. // Make sure the input expression also decays appropriately.
  12635. ExprResult Result = UsualUnaryConversions(E);
  12636. if (Result.isInvalid())
  12637. return ExprError();
  12638. E = Result.get();
  12639. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  12640. // If va_list is a record type and we are compiling in C++ mode,
  12641. // check the argument using reference binding.
  12642. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  12643. Context, Context.getLValueReferenceType(VaListType), false);
  12644. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  12645. if (Init.isInvalid())
  12646. return ExprError();
  12647. E = Init.getAs<Expr>();
  12648. } else {
  12649. // Otherwise, the va_list argument must be an l-value because
  12650. // it is modified by va_arg.
  12651. if (!E->isTypeDependent() &&
  12652. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  12653. return ExprError();
  12654. }
  12655. }
  12656. if (!IsMS && !E->isTypeDependent() &&
  12657. !Context.hasSameType(VaListType, E->getType()))
  12658. return ExprError(
  12659. Diag(E->getBeginLoc(),
  12660. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  12661. << OrigExpr->getType() << E->getSourceRange());
  12662. if (!TInfo->getType()->isDependentType()) {
  12663. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  12664. diag::err_second_parameter_to_va_arg_incomplete,
  12665. TInfo->getTypeLoc()))
  12666. return ExprError();
  12667. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  12668. TInfo->getType(),
  12669. diag::err_second_parameter_to_va_arg_abstract,
  12670. TInfo->getTypeLoc()))
  12671. return ExprError();
  12672. if (!TInfo->getType().isPODType(Context)) {
  12673. Diag(TInfo->getTypeLoc().getBeginLoc(),
  12674. TInfo->getType()->isObjCLifetimeType()
  12675. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  12676. : diag::warn_second_parameter_to_va_arg_not_pod)
  12677. << TInfo->getType()
  12678. << TInfo->getTypeLoc().getSourceRange();
  12679. }
  12680. // Check for va_arg where arguments of the given type will be promoted
  12681. // (i.e. this va_arg is guaranteed to have undefined behavior).
  12682. QualType PromoteType;
  12683. if (TInfo->getType()->isPromotableIntegerType()) {
  12684. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  12685. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  12686. PromoteType = QualType();
  12687. }
  12688. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  12689. PromoteType = Context.DoubleTy;
  12690. if (!PromoteType.isNull())
  12691. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  12692. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  12693. << TInfo->getType()
  12694. << PromoteType
  12695. << TInfo->getTypeLoc().getSourceRange());
  12696. }
  12697. QualType T = TInfo->getType().getNonLValueExprType(Context);
  12698. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  12699. }
  12700. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  12701. // The type of __null will be int or long, depending on the size of
  12702. // pointers on the target.
  12703. QualType Ty;
  12704. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  12705. if (pw == Context.getTargetInfo().getIntWidth())
  12706. Ty = Context.IntTy;
  12707. else if (pw == Context.getTargetInfo().getLongWidth())
  12708. Ty = Context.LongTy;
  12709. else if (pw == Context.getTargetInfo().getLongLongWidth())
  12710. Ty = Context.LongLongTy;
  12711. else {
  12712. llvm_unreachable("I don't know size of pointer!");
  12713. }
  12714. return new (Context) GNUNullExpr(Ty, TokenLoc);
  12715. }
  12716. ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12717. SourceLocation BuiltinLoc,
  12718. SourceLocation RPLoc) {
  12719. return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
  12720. }
  12721. ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
  12722. SourceLocation BuiltinLoc,
  12723. SourceLocation RPLoc,
  12724. DeclContext *ParentContext) {
  12725. return new (Context)
  12726. SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
  12727. }
  12728. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  12729. bool Diagnose) {
  12730. if (!getLangOpts().ObjC)
  12731. return false;
  12732. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  12733. if (!PT)
  12734. return false;
  12735. if (!PT->isObjCIdType()) {
  12736. // Check if the destination is the 'NSString' interface.
  12737. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  12738. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  12739. return false;
  12740. }
  12741. // Ignore any parens, implicit casts (should only be
  12742. // array-to-pointer decays), and not-so-opaque values. The last is
  12743. // important for making this trigger for property assignments.
  12744. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  12745. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  12746. if (OV->getSourceExpr())
  12747. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  12748. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  12749. if (!SL || !SL->isAscii())
  12750. return false;
  12751. if (Diagnose) {
  12752. Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
  12753. << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
  12754. Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
  12755. }
  12756. return true;
  12757. }
  12758. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  12759. const Expr *SrcExpr) {
  12760. if (!DstType->isFunctionPointerType() ||
  12761. !SrcExpr->getType()->isFunctionType())
  12762. return false;
  12763. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  12764. if (!DRE)
  12765. return false;
  12766. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  12767. if (!FD)
  12768. return false;
  12769. return !S.checkAddressOfFunctionIsAvailable(FD,
  12770. /*Complain=*/true,
  12771. SrcExpr->getBeginLoc());
  12772. }
  12773. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  12774. SourceLocation Loc,
  12775. QualType DstType, QualType SrcType,
  12776. Expr *SrcExpr, AssignmentAction Action,
  12777. bool *Complained) {
  12778. if (Complained)
  12779. *Complained = false;
  12780. // Decode the result (notice that AST's are still created for extensions).
  12781. bool CheckInferredResultType = false;
  12782. bool isInvalid = false;
  12783. unsigned DiagKind = 0;
  12784. FixItHint Hint;
  12785. ConversionFixItGenerator ConvHints;
  12786. bool MayHaveConvFixit = false;
  12787. bool MayHaveFunctionDiff = false;
  12788. const ObjCInterfaceDecl *IFace = nullptr;
  12789. const ObjCProtocolDecl *PDecl = nullptr;
  12790. switch (ConvTy) {
  12791. case Compatible:
  12792. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  12793. return false;
  12794. case PointerToInt:
  12795. DiagKind = diag::ext_typecheck_convert_pointer_int;
  12796. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12797. MayHaveConvFixit = true;
  12798. break;
  12799. case IntToPointer:
  12800. DiagKind = diag::ext_typecheck_convert_int_pointer;
  12801. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12802. MayHaveConvFixit = true;
  12803. break;
  12804. case IncompatiblePointer:
  12805. if (Action == AA_Passing_CFAudited)
  12806. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  12807. else if (SrcType->isFunctionPointerType() &&
  12808. DstType->isFunctionPointerType())
  12809. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  12810. else
  12811. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  12812. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  12813. SrcType->isObjCObjectPointerType();
  12814. if (Hint.isNull() && !CheckInferredResultType) {
  12815. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12816. }
  12817. else if (CheckInferredResultType) {
  12818. SrcType = SrcType.getUnqualifiedType();
  12819. DstType = DstType.getUnqualifiedType();
  12820. }
  12821. MayHaveConvFixit = true;
  12822. break;
  12823. case IncompatiblePointerSign:
  12824. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  12825. break;
  12826. case FunctionVoidPointer:
  12827. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  12828. break;
  12829. case IncompatiblePointerDiscardsQualifiers: {
  12830. // Perform array-to-pointer decay if necessary.
  12831. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  12832. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  12833. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  12834. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  12835. DiagKind = diag::err_typecheck_incompatible_address_space;
  12836. break;
  12837. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  12838. DiagKind = diag::err_typecheck_incompatible_ownership;
  12839. break;
  12840. }
  12841. llvm_unreachable("unknown error case for discarding qualifiers!");
  12842. // fallthrough
  12843. }
  12844. case CompatiblePointerDiscardsQualifiers:
  12845. // If the qualifiers lost were because we were applying the
  12846. // (deprecated) C++ conversion from a string literal to a char*
  12847. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  12848. // Ideally, this check would be performed in
  12849. // checkPointerTypesForAssignment. However, that would require a
  12850. // bit of refactoring (so that the second argument is an
  12851. // expression, rather than a type), which should be done as part
  12852. // of a larger effort to fix checkPointerTypesForAssignment for
  12853. // C++ semantics.
  12854. if (getLangOpts().CPlusPlus &&
  12855. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  12856. return false;
  12857. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  12858. break;
  12859. case IncompatibleNestedPointerQualifiers:
  12860. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  12861. break;
  12862. case IncompatibleNestedPointerAddressSpaceMismatch:
  12863. DiagKind = diag::err_typecheck_incompatible_nested_address_space;
  12864. break;
  12865. case IntToBlockPointer:
  12866. DiagKind = diag::err_int_to_block_pointer;
  12867. break;
  12868. case IncompatibleBlockPointer:
  12869. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  12870. break;
  12871. case IncompatibleObjCQualifiedId: {
  12872. if (SrcType->isObjCQualifiedIdType()) {
  12873. const ObjCObjectPointerType *srcOPT =
  12874. SrcType->getAs<ObjCObjectPointerType>();
  12875. for (auto *srcProto : srcOPT->quals()) {
  12876. PDecl = srcProto;
  12877. break;
  12878. }
  12879. if (const ObjCInterfaceType *IFaceT =
  12880. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12881. IFace = IFaceT->getDecl();
  12882. }
  12883. else if (DstType->isObjCQualifiedIdType()) {
  12884. const ObjCObjectPointerType *dstOPT =
  12885. DstType->getAs<ObjCObjectPointerType>();
  12886. for (auto *dstProto : dstOPT->quals()) {
  12887. PDecl = dstProto;
  12888. break;
  12889. }
  12890. if (const ObjCInterfaceType *IFaceT =
  12891. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  12892. IFace = IFaceT->getDecl();
  12893. }
  12894. DiagKind = diag::warn_incompatible_qualified_id;
  12895. break;
  12896. }
  12897. case IncompatibleVectors:
  12898. DiagKind = diag::warn_incompatible_vectors;
  12899. break;
  12900. case IncompatibleObjCWeakRef:
  12901. DiagKind = diag::err_arc_weak_unavailable_assign;
  12902. break;
  12903. case Incompatible:
  12904. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  12905. if (Complained)
  12906. *Complained = true;
  12907. return true;
  12908. }
  12909. DiagKind = diag::err_typecheck_convert_incompatible;
  12910. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  12911. MayHaveConvFixit = true;
  12912. isInvalid = true;
  12913. MayHaveFunctionDiff = true;
  12914. break;
  12915. }
  12916. QualType FirstType, SecondType;
  12917. switch (Action) {
  12918. case AA_Assigning:
  12919. case AA_Initializing:
  12920. // The destination type comes first.
  12921. FirstType = DstType;
  12922. SecondType = SrcType;
  12923. break;
  12924. case AA_Returning:
  12925. case AA_Passing:
  12926. case AA_Passing_CFAudited:
  12927. case AA_Converting:
  12928. case AA_Sending:
  12929. case AA_Casting:
  12930. // The source type comes first.
  12931. FirstType = SrcType;
  12932. SecondType = DstType;
  12933. break;
  12934. }
  12935. PartialDiagnostic FDiag = PDiag(DiagKind);
  12936. if (Action == AA_Passing_CFAudited)
  12937. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  12938. else
  12939. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  12940. // If we can fix the conversion, suggest the FixIts.
  12941. assert(ConvHints.isNull() || Hint.isNull());
  12942. if (!ConvHints.isNull()) {
  12943. for (FixItHint &H : ConvHints.Hints)
  12944. FDiag << H;
  12945. } else {
  12946. FDiag << Hint;
  12947. }
  12948. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  12949. if (MayHaveFunctionDiff)
  12950. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  12951. Diag(Loc, FDiag);
  12952. if (DiagKind == diag::warn_incompatible_qualified_id &&
  12953. PDecl && IFace && !IFace->hasDefinition())
  12954. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  12955. << IFace << PDecl;
  12956. if (SecondType == Context.OverloadTy)
  12957. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  12958. FirstType, /*TakingAddress=*/true);
  12959. if (CheckInferredResultType)
  12960. EmitRelatedResultTypeNote(SrcExpr);
  12961. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  12962. EmitRelatedResultTypeNoteForReturn(DstType);
  12963. if (Complained)
  12964. *Complained = true;
  12965. return isInvalid;
  12966. }
  12967. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12968. llvm::APSInt *Result) {
  12969. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  12970. public:
  12971. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12972. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  12973. }
  12974. } Diagnoser;
  12975. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  12976. }
  12977. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  12978. llvm::APSInt *Result,
  12979. unsigned DiagID,
  12980. bool AllowFold) {
  12981. class IDDiagnoser : public VerifyICEDiagnoser {
  12982. unsigned DiagID;
  12983. public:
  12984. IDDiagnoser(unsigned DiagID)
  12985. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  12986. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  12987. S.Diag(Loc, DiagID) << SR;
  12988. }
  12989. } Diagnoser(DiagID);
  12990. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  12991. }
  12992. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  12993. SourceRange SR) {
  12994. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  12995. }
  12996. ExprResult
  12997. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  12998. VerifyICEDiagnoser &Diagnoser,
  12999. bool AllowFold) {
  13000. SourceLocation DiagLoc = E->getBeginLoc();
  13001. if (getLangOpts().CPlusPlus11) {
  13002. // C++11 [expr.const]p5:
  13003. // If an expression of literal class type is used in a context where an
  13004. // integral constant expression is required, then that class type shall
  13005. // have a single non-explicit conversion function to an integral or
  13006. // unscoped enumeration type
  13007. ExprResult Converted;
  13008. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  13009. public:
  13010. CXX11ConvertDiagnoser(bool Silent)
  13011. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  13012. Silent, true) {}
  13013. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  13014. QualType T) override {
  13015. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  13016. }
  13017. SemaDiagnosticBuilder diagnoseIncomplete(
  13018. Sema &S, SourceLocation Loc, QualType T) override {
  13019. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  13020. }
  13021. SemaDiagnosticBuilder diagnoseExplicitConv(
  13022. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13023. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  13024. }
  13025. SemaDiagnosticBuilder noteExplicitConv(
  13026. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13027. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13028. << ConvTy->isEnumeralType() << ConvTy;
  13029. }
  13030. SemaDiagnosticBuilder diagnoseAmbiguous(
  13031. Sema &S, SourceLocation Loc, QualType T) override {
  13032. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  13033. }
  13034. SemaDiagnosticBuilder noteAmbiguous(
  13035. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  13036. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  13037. << ConvTy->isEnumeralType() << ConvTy;
  13038. }
  13039. SemaDiagnosticBuilder diagnoseConversion(
  13040. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  13041. llvm_unreachable("conversion functions are permitted");
  13042. }
  13043. } ConvertDiagnoser(Diagnoser.Suppress);
  13044. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  13045. ConvertDiagnoser);
  13046. if (Converted.isInvalid())
  13047. return Converted;
  13048. E = Converted.get();
  13049. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  13050. return ExprError();
  13051. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  13052. // An ICE must be of integral or unscoped enumeration type.
  13053. if (!Diagnoser.Suppress)
  13054. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13055. return ExprError();
  13056. }
  13057. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  13058. // in the non-ICE case.
  13059. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  13060. if (Result)
  13061. *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
  13062. if (!isa<ConstantExpr>(E))
  13063. E = ConstantExpr::Create(Context, E);
  13064. return E;
  13065. }
  13066. Expr::EvalResult EvalResult;
  13067. SmallVector<PartialDiagnosticAt, 8> Notes;
  13068. EvalResult.Diag = &Notes;
  13069. // Try to evaluate the expression, and produce diagnostics explaining why it's
  13070. // not a constant expression as a side-effect.
  13071. bool Folded =
  13072. E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
  13073. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  13074. if (!isa<ConstantExpr>(E))
  13075. E = ConstantExpr::Create(Context, E, EvalResult.Val);
  13076. // In C++11, we can rely on diagnostics being produced for any expression
  13077. // which is not a constant expression. If no diagnostics were produced, then
  13078. // this is a constant expression.
  13079. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  13080. if (Result)
  13081. *Result = EvalResult.Val.getInt();
  13082. return E;
  13083. }
  13084. // If our only note is the usual "invalid subexpression" note, just point
  13085. // the caret at its location rather than producing an essentially
  13086. // redundant note.
  13087. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  13088. diag::note_invalid_subexpr_in_const_expr) {
  13089. DiagLoc = Notes[0].first;
  13090. Notes.clear();
  13091. }
  13092. if (!Folded || !AllowFold) {
  13093. if (!Diagnoser.Suppress) {
  13094. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  13095. for (const PartialDiagnosticAt &Note : Notes)
  13096. Diag(Note.first, Note.second);
  13097. }
  13098. return ExprError();
  13099. }
  13100. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  13101. for (const PartialDiagnosticAt &Note : Notes)
  13102. Diag(Note.first, Note.second);
  13103. if (Result)
  13104. *Result = EvalResult.Val.getInt();
  13105. return E;
  13106. }
  13107. namespace {
  13108. // Handle the case where we conclude a expression which we speculatively
  13109. // considered to be unevaluated is actually evaluated.
  13110. class TransformToPE : public TreeTransform<TransformToPE> {
  13111. typedef TreeTransform<TransformToPE> BaseTransform;
  13112. public:
  13113. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  13114. // Make sure we redo semantic analysis
  13115. bool AlwaysRebuild() { return true; }
  13116. bool ReplacingOriginal() { return true; }
  13117. // We need to special-case DeclRefExprs referring to FieldDecls which
  13118. // are not part of a member pointer formation; normal TreeTransforming
  13119. // doesn't catch this case because of the way we represent them in the AST.
  13120. // FIXME: This is a bit ugly; is it really the best way to handle this
  13121. // case?
  13122. //
  13123. // Error on DeclRefExprs referring to FieldDecls.
  13124. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  13125. if (isa<FieldDecl>(E->getDecl()) &&
  13126. !SemaRef.isUnevaluatedContext())
  13127. return SemaRef.Diag(E->getLocation(),
  13128. diag::err_invalid_non_static_member_use)
  13129. << E->getDecl() << E->getSourceRange();
  13130. return BaseTransform::TransformDeclRefExpr(E);
  13131. }
  13132. // Exception: filter out member pointer formation
  13133. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  13134. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  13135. return E;
  13136. return BaseTransform::TransformUnaryOperator(E);
  13137. }
  13138. // The body of a lambda-expression is in a separate expression evaluation
  13139. // context so never needs to be transformed.
  13140. // FIXME: Ideally we wouldn't transform the closure type either, and would
  13141. // just recreate the capture expressions and lambda expression.
  13142. StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
  13143. return SkipLambdaBody(E, Body);
  13144. }
  13145. };
  13146. }
  13147. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  13148. assert(isUnevaluatedContext() &&
  13149. "Should only transform unevaluated expressions");
  13150. ExprEvalContexts.back().Context =
  13151. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  13152. if (isUnevaluatedContext())
  13153. return E;
  13154. return TransformToPE(*this).TransformExpr(E);
  13155. }
  13156. void
  13157. Sema::PushExpressionEvaluationContext(
  13158. ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
  13159. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13160. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  13161. LambdaContextDecl, ExprContext);
  13162. Cleanup.reset();
  13163. if (!MaybeODRUseExprs.empty())
  13164. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  13165. }
  13166. void
  13167. Sema::PushExpressionEvaluationContext(
  13168. ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
  13169. ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
  13170. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  13171. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
  13172. }
  13173. namespace {
  13174. const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
  13175. PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
  13176. if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
  13177. if (E->getOpcode() == UO_Deref)
  13178. return CheckPossibleDeref(S, E->getSubExpr());
  13179. } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
  13180. return CheckPossibleDeref(S, E->getBase());
  13181. } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
  13182. return CheckPossibleDeref(S, E->getBase());
  13183. } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
  13184. QualType Inner;
  13185. QualType Ty = E->getType();
  13186. if (const auto *Ptr = Ty->getAs<PointerType>())
  13187. Inner = Ptr->getPointeeType();
  13188. else if (const auto *Arr = S.Context.getAsArrayType(Ty))
  13189. Inner = Arr->getElementType();
  13190. else
  13191. return nullptr;
  13192. if (Inner->hasAttr(attr::NoDeref))
  13193. return E;
  13194. }
  13195. return nullptr;
  13196. }
  13197. } // namespace
  13198. void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
  13199. for (const Expr *E : Rec.PossibleDerefs) {
  13200. const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
  13201. if (DeclRef) {
  13202. const ValueDecl *Decl = DeclRef->getDecl();
  13203. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
  13204. << Decl->getName() << E->getSourceRange();
  13205. Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
  13206. } else {
  13207. Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
  13208. << E->getSourceRange();
  13209. }
  13210. }
  13211. Rec.PossibleDerefs.clear();
  13212. }
  13213. void Sema::PopExpressionEvaluationContext() {
  13214. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  13215. unsigned NumTypos = Rec.NumTypos;
  13216. if (!Rec.Lambdas.empty()) {
  13217. using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
  13218. if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
  13219. (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
  13220. unsigned D;
  13221. if (Rec.isUnevaluated()) {
  13222. // C++11 [expr.prim.lambda]p2:
  13223. // A lambda-expression shall not appear in an unevaluated operand
  13224. // (Clause 5).
  13225. D = diag::err_lambda_unevaluated_operand;
  13226. } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
  13227. // C++1y [expr.const]p2:
  13228. // A conditional-expression e is a core constant expression unless the
  13229. // evaluation of e, following the rules of the abstract machine, would
  13230. // evaluate [...] a lambda-expression.
  13231. D = diag::err_lambda_in_constant_expression;
  13232. } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
  13233. // C++17 [expr.prim.lamda]p2:
  13234. // A lambda-expression shall not appear [...] in a template-argument.
  13235. D = diag::err_lambda_in_invalid_context;
  13236. } else
  13237. llvm_unreachable("Couldn't infer lambda error message.");
  13238. for (const auto *L : Rec.Lambdas)
  13239. Diag(L->getBeginLoc(), D);
  13240. }
  13241. }
  13242. WarnOnPendingNoDerefs(Rec);
  13243. // When are coming out of an unevaluated context, clear out any
  13244. // temporaries that we may have created as part of the evaluation of
  13245. // the expression in that context: they aren't relevant because they
  13246. // will never be constructed.
  13247. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  13248. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  13249. ExprCleanupObjects.end());
  13250. Cleanup = Rec.ParentCleanup;
  13251. CleanupVarDeclMarking();
  13252. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  13253. // Otherwise, merge the contexts together.
  13254. } else {
  13255. Cleanup.mergeFrom(Rec.ParentCleanup);
  13256. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  13257. Rec.SavedMaybeODRUseExprs.end());
  13258. }
  13259. // Pop the current expression evaluation context off the stack.
  13260. ExprEvalContexts.pop_back();
  13261. // The global expression evaluation context record is never popped.
  13262. ExprEvalContexts.back().NumTypos += NumTypos;
  13263. }
  13264. void Sema::DiscardCleanupsInEvaluationContext() {
  13265. ExprCleanupObjects.erase(
  13266. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  13267. ExprCleanupObjects.end());
  13268. Cleanup.reset();
  13269. MaybeODRUseExprs.clear();
  13270. }
  13271. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  13272. ExprResult Result = CheckPlaceholderExpr(E);
  13273. if (Result.isInvalid())
  13274. return ExprError();
  13275. E = Result.get();
  13276. if (!E->getType()->isVariablyModifiedType())
  13277. return E;
  13278. return TransformToPotentiallyEvaluated(E);
  13279. }
  13280. /// Are we in a context that is potentially constant evaluated per C++20
  13281. /// [expr.const]p12?
  13282. static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
  13283. /// C++2a [expr.const]p12:
  13284. // An expression or conversion is potentially constant evaluated if it is
  13285. switch (SemaRef.ExprEvalContexts.back().Context) {
  13286. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13287. // -- a manifestly constant-evaluated expression,
  13288. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13289. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13290. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13291. // -- a potentially-evaluated expression,
  13292. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13293. // -- an immediate subexpression of a braced-init-list,
  13294. // -- [FIXME] an expression of the form & cast-expression that occurs
  13295. // within a templated entity
  13296. // -- a subexpression of one of the above that is not a subexpression of
  13297. // a nested unevaluated operand.
  13298. return true;
  13299. case Sema::ExpressionEvaluationContext::Unevaluated:
  13300. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13301. // Expressions in this context are never evaluated.
  13302. return false;
  13303. }
  13304. llvm_unreachable("Invalid context");
  13305. }
  13306. /// Return true if this function has a calling convention that requires mangling
  13307. /// in the size of the parameter pack.
  13308. static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
  13309. // These manglings don't do anything on non-Windows or non-x86 platforms, so
  13310. // we don't need parameter type sizes.
  13311. const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
  13312. if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
  13313. TT.getArch() != llvm::Triple::x86_64))
  13314. return false;
  13315. // If this is C++ and this isn't an extern "C" function, parameters do not
  13316. // need to be complete. In this case, C++ mangling will apply, which doesn't
  13317. // use the size of the parameters.
  13318. if (S.getLangOpts().CPlusPlus && !FD->isExternC())
  13319. return false;
  13320. // Stdcall, fastcall, and vectorcall need this special treatment.
  13321. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13322. switch (CC) {
  13323. case CC_X86StdCall:
  13324. case CC_X86FastCall:
  13325. case CC_X86VectorCall:
  13326. return true;
  13327. default:
  13328. break;
  13329. }
  13330. return false;
  13331. }
  13332. /// Require that all of the parameter types of function be complete. Normally,
  13333. /// parameter types are only required to be complete when a function is called
  13334. /// or defined, but to mangle functions with certain calling conventions, the
  13335. /// mangler needs to know the size of the parameter list. In this situation,
  13336. /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
  13337. /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
  13338. /// result in a linker error. Clang doesn't implement this behavior, and instead
  13339. /// attempts to error at compile time.
  13340. static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
  13341. SourceLocation Loc) {
  13342. class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
  13343. FunctionDecl *FD;
  13344. ParmVarDecl *Param;
  13345. public:
  13346. ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
  13347. : FD(FD), Param(Param) {}
  13348. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13349. CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
  13350. StringRef CCName;
  13351. switch (CC) {
  13352. case CC_X86StdCall:
  13353. CCName = "stdcall";
  13354. break;
  13355. case CC_X86FastCall:
  13356. CCName = "fastcall";
  13357. break;
  13358. case CC_X86VectorCall:
  13359. CCName = "vectorcall";
  13360. break;
  13361. default:
  13362. llvm_unreachable("CC does not need mangling");
  13363. }
  13364. S.Diag(Loc, diag::err_cconv_incomplete_param_type)
  13365. << Param->getDeclName() << FD->getDeclName() << CCName;
  13366. }
  13367. };
  13368. for (ParmVarDecl *Param : FD->parameters()) {
  13369. ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
  13370. S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
  13371. }
  13372. }
  13373. namespace {
  13374. enum class OdrUseContext {
  13375. /// Declarations in this context are not odr-used.
  13376. None,
  13377. /// Declarations in this context are formally odr-used, but this is a
  13378. /// dependent context.
  13379. Dependent,
  13380. /// Declarations in this context are odr-used but not actually used (yet).
  13381. FormallyOdrUsed,
  13382. /// Declarations in this context are used.
  13383. Used
  13384. };
  13385. }
  13386. /// Are we within a context in which references to resolved functions or to
  13387. /// variables result in odr-use?
  13388. static OdrUseContext isOdrUseContext(Sema &SemaRef) {
  13389. OdrUseContext Result;
  13390. switch (SemaRef.ExprEvalContexts.back().Context) {
  13391. case Sema::ExpressionEvaluationContext::Unevaluated:
  13392. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  13393. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  13394. return OdrUseContext::None;
  13395. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  13396. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  13397. Result = OdrUseContext::Used;
  13398. break;
  13399. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  13400. Result = OdrUseContext::FormallyOdrUsed;
  13401. break;
  13402. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13403. // A default argument formally results in odr-use, but doesn't actually
  13404. // result in a use in any real sense until it itself is used.
  13405. Result = OdrUseContext::FormallyOdrUsed;
  13406. break;
  13407. }
  13408. if (SemaRef.CurContext->isDependentContext())
  13409. return OdrUseContext::Dependent;
  13410. return Result;
  13411. }
  13412. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  13413. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  13414. return Func->isConstexpr() &&
  13415. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  13416. }
  13417. /// Mark a function referenced, and check whether it is odr-used
  13418. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  13419. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  13420. bool MightBeOdrUse) {
  13421. assert(Func && "No function?");
  13422. Func->setReferenced();
  13423. // Recursive functions aren't really used until they're used from some other
  13424. // context.
  13425. bool IsRecursiveCall = CurContext == Func;
  13426. // C++11 [basic.def.odr]p3:
  13427. // A function whose name appears as a potentially-evaluated expression is
  13428. // odr-used if it is the unique lookup result or the selected member of a
  13429. // set of overloaded functions [...].
  13430. //
  13431. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  13432. // can just check that here.
  13433. OdrUseContext OdrUse =
  13434. MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
  13435. if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
  13436. OdrUse = OdrUseContext::FormallyOdrUsed;
  13437. // Trivial default constructors and destructors are never actually used.
  13438. // FIXME: What about other special members?
  13439. if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
  13440. OdrUse == OdrUseContext::Used) {
  13441. if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
  13442. if (Constructor->isDefaultConstructor())
  13443. OdrUse = OdrUseContext::FormallyOdrUsed;
  13444. if (isa<CXXDestructorDecl>(Func))
  13445. OdrUse = OdrUseContext::FormallyOdrUsed;
  13446. }
  13447. // C++20 [expr.const]p12:
  13448. // A function [...] is needed for constant evaluation if it is [...] a
  13449. // constexpr function that is named by an expression that is potentially
  13450. // constant evaluated
  13451. bool NeededForConstantEvaluation =
  13452. isPotentiallyConstantEvaluatedContext(*this) &&
  13453. isImplicitlyDefinableConstexprFunction(Func);
  13454. // Determine whether we require a function definition to exist, per
  13455. // C++11 [temp.inst]p3:
  13456. // Unless a function template specialization has been explicitly
  13457. // instantiated or explicitly specialized, the function template
  13458. // specialization is implicitly instantiated when the specialization is
  13459. // referenced in a context that requires a function definition to exist.
  13460. // C++20 [temp.inst]p7:
  13461. // The existence of a definition of a [...] function is considered to
  13462. // affect the semantics of the program if the [...] function is needed for
  13463. // constant evaluation by an expression
  13464. // C++20 [basic.def.odr]p10:
  13465. // Every program shall contain exactly one definition of every non-inline
  13466. // function or variable that is odr-used in that program outside of a
  13467. // discarded statement
  13468. // C++20 [special]p1:
  13469. // The implementation will implicitly define [defaulted special members]
  13470. // if they are odr-used or needed for constant evaluation.
  13471. //
  13472. // Note that we skip the implicit instantiation of templates that are only
  13473. // used in unused default arguments or by recursive calls to themselves.
  13474. // This is formally non-conforming, but seems reasonable in practice.
  13475. bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
  13476. NeededForConstantEvaluation);
  13477. // C++14 [temp.expl.spec]p6:
  13478. // If a template [...] is explicitly specialized then that specialization
  13479. // shall be declared before the first use of that specialization that would
  13480. // cause an implicit instantiation to take place, in every translation unit
  13481. // in which such a use occurs
  13482. if (NeedDefinition &&
  13483. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  13484. Func->getMemberSpecializationInfo()))
  13485. checkSpecializationVisibility(Loc, Func);
  13486. // C++14 [except.spec]p17:
  13487. // An exception-specification is considered to be needed when:
  13488. // - the function is odr-used or, if it appears in an unevaluated operand,
  13489. // would be odr-used if the expression were potentially-evaluated;
  13490. //
  13491. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  13492. // function is a pure virtual function we're calling, and in that case the
  13493. // function was selected by overload resolution and we need to resolve its
  13494. // exception specification for a different reason.
  13495. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  13496. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  13497. ResolveExceptionSpec(Loc, FPT);
  13498. if (getLangOpts().CUDA)
  13499. CheckCUDACall(Loc, Func);
  13500. // If we need a definition, try to create one.
  13501. if (NeedDefinition && !Func->getBody()) {
  13502. runWithSufficientStackSpace(Loc, [&] {
  13503. if (CXXConstructorDecl *Constructor =
  13504. dyn_cast<CXXConstructorDecl>(Func)) {
  13505. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  13506. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  13507. if (Constructor->isDefaultConstructor()) {
  13508. if (Constructor->isTrivial() &&
  13509. !Constructor->hasAttr<DLLExportAttr>())
  13510. return;
  13511. DefineImplicitDefaultConstructor(Loc, Constructor);
  13512. } else if (Constructor->isCopyConstructor()) {
  13513. DefineImplicitCopyConstructor(Loc, Constructor);
  13514. } else if (Constructor->isMoveConstructor()) {
  13515. DefineImplicitMoveConstructor(Loc, Constructor);
  13516. }
  13517. } else if (Constructor->getInheritedConstructor()) {
  13518. DefineInheritingConstructor(Loc, Constructor);
  13519. }
  13520. } else if (CXXDestructorDecl *Destructor =
  13521. dyn_cast<CXXDestructorDecl>(Func)) {
  13522. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  13523. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  13524. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  13525. return;
  13526. DefineImplicitDestructor(Loc, Destructor);
  13527. }
  13528. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  13529. MarkVTableUsed(Loc, Destructor->getParent());
  13530. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  13531. if (MethodDecl->isOverloadedOperator() &&
  13532. MethodDecl->getOverloadedOperator() == OO_Equal) {
  13533. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  13534. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  13535. if (MethodDecl->isCopyAssignmentOperator())
  13536. DefineImplicitCopyAssignment(Loc, MethodDecl);
  13537. else if (MethodDecl->isMoveAssignmentOperator())
  13538. DefineImplicitMoveAssignment(Loc, MethodDecl);
  13539. }
  13540. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  13541. MethodDecl->getParent()->isLambda()) {
  13542. CXXConversionDecl *Conversion =
  13543. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  13544. if (Conversion->isLambdaToBlockPointerConversion())
  13545. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  13546. else
  13547. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  13548. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  13549. MarkVTableUsed(Loc, MethodDecl->getParent());
  13550. }
  13551. // Implicit instantiation of function templates and member functions of
  13552. // class templates.
  13553. if (Func->isImplicitlyInstantiable()) {
  13554. TemplateSpecializationKind TSK =
  13555. Func->getTemplateSpecializationKindForInstantiation();
  13556. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  13557. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13558. if (FirstInstantiation) {
  13559. PointOfInstantiation = Loc;
  13560. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13561. } else if (TSK != TSK_ImplicitInstantiation) {
  13562. // Use the point of use as the point of instantiation, instead of the
  13563. // point of explicit instantiation (which we track as the actual point
  13564. // of instantiation). This gives better backtraces in diagnostics.
  13565. PointOfInstantiation = Loc;
  13566. }
  13567. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  13568. Func->isConstexpr()) {
  13569. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  13570. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  13571. CodeSynthesisContexts.size())
  13572. PendingLocalImplicitInstantiations.push_back(
  13573. std::make_pair(Func, PointOfInstantiation));
  13574. else if (Func->isConstexpr())
  13575. // Do not defer instantiations of constexpr functions, to avoid the
  13576. // expression evaluator needing to call back into Sema if it sees a
  13577. // call to such a function.
  13578. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  13579. else {
  13580. Func->setInstantiationIsPending(true);
  13581. PendingInstantiations.push_back(
  13582. std::make_pair(Func, PointOfInstantiation));
  13583. // Notify the consumer that a function was implicitly instantiated.
  13584. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  13585. }
  13586. }
  13587. } else {
  13588. // Walk redefinitions, as some of them may be instantiable.
  13589. for (auto i : Func->redecls()) {
  13590. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  13591. MarkFunctionReferenced(Loc, i, MightBeOdrUse);
  13592. }
  13593. }
  13594. });
  13595. }
  13596. // If this is the first "real" use, act on that.
  13597. if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
  13598. // Keep track of used but undefined functions.
  13599. if (!Func->isDefined()) {
  13600. if (mightHaveNonExternalLinkage(Func))
  13601. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13602. else if (Func->getMostRecentDecl()->isInlined() &&
  13603. !LangOpts.GNUInline &&
  13604. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  13605. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13606. else if (isExternalWithNoLinkageType(Func))
  13607. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  13608. }
  13609. // Some x86 Windows calling conventions mangle the size of the parameter
  13610. // pack into the name. Computing the size of the parameters requires the
  13611. // parameter types to be complete. Check that now.
  13612. if (funcHasParameterSizeMangling(*this, Func))
  13613. CheckCompleteParameterTypesForMangler(*this, Func, Loc);
  13614. Func->markUsed(Context);
  13615. }
  13616. if (LangOpts.OpenMP) {
  13617. if (LangOpts.OpenMPIsDevice)
  13618. checkOpenMPDeviceFunction(Loc, Func);
  13619. else
  13620. checkOpenMPHostFunction(Loc, Func);
  13621. }
  13622. }
  13623. /// Directly mark a variable odr-used. Given a choice, prefer to use
  13624. /// MarkVariableReferenced since it does additional checks and then
  13625. /// calls MarkVarDeclODRUsed.
  13626. /// If the variable must be captured:
  13627. /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
  13628. /// - else capture it in the DeclContext that maps to the
  13629. /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
  13630. static void
  13631. MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
  13632. const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
  13633. // Keep track of used but undefined variables.
  13634. // FIXME: We shouldn't suppress this warning for static data members.
  13635. if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
  13636. (!Var->isExternallyVisible() || Var->isInline() ||
  13637. SemaRef.isExternalWithNoLinkageType(Var)) &&
  13638. !(Var->isStaticDataMember() && Var->hasInit())) {
  13639. SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
  13640. if (old.isInvalid())
  13641. old = Loc;
  13642. }
  13643. QualType CaptureType, DeclRefType;
  13644. if (SemaRef.LangOpts.OpenMP)
  13645. SemaRef.tryCaptureOpenMPLambdas(Var);
  13646. SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
  13647. /*EllipsisLoc*/ SourceLocation(),
  13648. /*BuildAndDiagnose*/ true,
  13649. CaptureType, DeclRefType,
  13650. FunctionScopeIndexToStopAt);
  13651. Var->markUsed(SemaRef.Context);
  13652. }
  13653. void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
  13654. SourceLocation Loc,
  13655. unsigned CapturingScopeIndex) {
  13656. MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
  13657. }
  13658. static void
  13659. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  13660. ValueDecl *var, DeclContext *DC) {
  13661. DeclContext *VarDC = var->getDeclContext();
  13662. // If the parameter still belongs to the translation unit, then
  13663. // we're actually just using one parameter in the declaration of
  13664. // the next.
  13665. if (isa<ParmVarDecl>(var) &&
  13666. isa<TranslationUnitDecl>(VarDC))
  13667. return;
  13668. // For C code, don't diagnose about capture if we're not actually in code
  13669. // right now; it's impossible to write a non-constant expression outside of
  13670. // function context, so we'll get other (more useful) diagnostics later.
  13671. //
  13672. // For C++, things get a bit more nasty... it would be nice to suppress this
  13673. // diagnostic for certain cases like using a local variable in an array bound
  13674. // for a member of a local class, but the correct predicate is not obvious.
  13675. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  13676. return;
  13677. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  13678. unsigned ContextKind = 3; // unknown
  13679. if (isa<CXXMethodDecl>(VarDC) &&
  13680. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  13681. ContextKind = 2;
  13682. } else if (isa<FunctionDecl>(VarDC)) {
  13683. ContextKind = 0;
  13684. } else if (isa<BlockDecl>(VarDC)) {
  13685. ContextKind = 1;
  13686. }
  13687. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  13688. << var << ValueKind << ContextKind << VarDC;
  13689. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  13690. << var;
  13691. // FIXME: Add additional diagnostic info about class etc. which prevents
  13692. // capture.
  13693. }
  13694. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  13695. bool &SubCapturesAreNested,
  13696. QualType &CaptureType,
  13697. QualType &DeclRefType) {
  13698. // Check whether we've already captured it.
  13699. if (CSI->CaptureMap.count(Var)) {
  13700. // If we found a capture, any subcaptures are nested.
  13701. SubCapturesAreNested = true;
  13702. // Retrieve the capture type for this variable.
  13703. CaptureType = CSI->getCapture(Var).getCaptureType();
  13704. // Compute the type of an expression that refers to this variable.
  13705. DeclRefType = CaptureType.getNonReferenceType();
  13706. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  13707. // are mutable in the sense that user can change their value - they are
  13708. // private instances of the captured declarations.
  13709. const Capture &Cap = CSI->getCapture(Var);
  13710. if (Cap.isCopyCapture() &&
  13711. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  13712. !(isa<CapturedRegionScopeInfo>(CSI) &&
  13713. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  13714. DeclRefType.addConst();
  13715. return true;
  13716. }
  13717. return false;
  13718. }
  13719. // Only block literals, captured statements, and lambda expressions can
  13720. // capture; other scopes don't work.
  13721. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  13722. SourceLocation Loc,
  13723. const bool Diagnose, Sema &S) {
  13724. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  13725. return getLambdaAwareParentOfDeclContext(DC);
  13726. else if (Var->hasLocalStorage()) {
  13727. if (Diagnose)
  13728. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  13729. }
  13730. return nullptr;
  13731. }
  13732. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  13733. // certain types of variables (unnamed, variably modified types etc.)
  13734. // so check for eligibility.
  13735. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  13736. SourceLocation Loc,
  13737. const bool Diagnose, Sema &S) {
  13738. bool IsBlock = isa<BlockScopeInfo>(CSI);
  13739. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  13740. // Lambdas are not allowed to capture unnamed variables
  13741. // (e.g. anonymous unions).
  13742. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  13743. // assuming that's the intent.
  13744. if (IsLambda && !Var->getDeclName()) {
  13745. if (Diagnose) {
  13746. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  13747. S.Diag(Var->getLocation(), diag::note_declared_at);
  13748. }
  13749. return false;
  13750. }
  13751. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  13752. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  13753. if (Diagnose) {
  13754. S.Diag(Loc, diag::err_ref_vm_type);
  13755. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13756. << Var->getDeclName();
  13757. }
  13758. return false;
  13759. }
  13760. // Prohibit structs with flexible array members too.
  13761. // We cannot capture what is in the tail end of the struct.
  13762. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  13763. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  13764. if (Diagnose) {
  13765. if (IsBlock)
  13766. S.Diag(Loc, diag::err_ref_flexarray_type);
  13767. else
  13768. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  13769. << Var->getDeclName();
  13770. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13771. << Var->getDeclName();
  13772. }
  13773. return false;
  13774. }
  13775. }
  13776. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13777. // Lambdas and captured statements are not allowed to capture __block
  13778. // variables; they don't support the expected semantics.
  13779. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  13780. if (Diagnose) {
  13781. S.Diag(Loc, diag::err_capture_block_variable)
  13782. << Var->getDeclName() << !IsLambda;
  13783. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13784. << Var->getDeclName();
  13785. }
  13786. return false;
  13787. }
  13788. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  13789. if (S.getLangOpts().OpenCL && IsBlock &&
  13790. Var->getType()->isBlockPointerType()) {
  13791. if (Diagnose)
  13792. S.Diag(Loc, diag::err_opencl_block_ref_block);
  13793. return false;
  13794. }
  13795. return true;
  13796. }
  13797. // Returns true if the capture by block was successful.
  13798. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  13799. SourceLocation Loc,
  13800. const bool BuildAndDiagnose,
  13801. QualType &CaptureType,
  13802. QualType &DeclRefType,
  13803. const bool Nested,
  13804. Sema &S, bool Invalid) {
  13805. bool ByRef = false;
  13806. // Blocks are not allowed to capture arrays, excepting OpenCL.
  13807. // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
  13808. // (decayed to pointers).
  13809. if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
  13810. if (BuildAndDiagnose) {
  13811. S.Diag(Loc, diag::err_ref_array_type);
  13812. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13813. << Var->getDeclName();
  13814. Invalid = true;
  13815. } else {
  13816. return false;
  13817. }
  13818. }
  13819. // Forbid the block-capture of autoreleasing variables.
  13820. if (!Invalid &&
  13821. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13822. if (BuildAndDiagnose) {
  13823. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  13824. << /*block*/ 0;
  13825. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13826. << Var->getDeclName();
  13827. Invalid = true;
  13828. } else {
  13829. return false;
  13830. }
  13831. }
  13832. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  13833. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  13834. // This function finds out whether there is an AttributedType of kind
  13835. // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
  13836. // attr::ObjCOwnership implies __autoreleasing was explicitly specified
  13837. // rather than being added implicitly by the compiler.
  13838. auto IsObjCOwnershipAttributedType = [](QualType Ty) {
  13839. while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
  13840. if (AttrTy->getAttrKind() == attr::ObjCOwnership)
  13841. return true;
  13842. // Peel off AttributedTypes that are not of kind ObjCOwnership.
  13843. Ty = AttrTy->getModifiedType();
  13844. }
  13845. return false;
  13846. };
  13847. QualType PointeeTy = PT->getPointeeType();
  13848. if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
  13849. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  13850. !IsObjCOwnershipAttributedType(PointeeTy)) {
  13851. if (BuildAndDiagnose) {
  13852. SourceLocation VarLoc = Var->getLocation();
  13853. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  13854. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  13855. }
  13856. }
  13857. }
  13858. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  13859. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  13860. (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
  13861. // Block capture by reference does not change the capture or
  13862. // declaration reference types.
  13863. ByRef = true;
  13864. } else {
  13865. // Block capture by copy introduces 'const'.
  13866. CaptureType = CaptureType.getNonReferenceType().withConst();
  13867. DeclRefType = CaptureType;
  13868. }
  13869. // Actually capture the variable.
  13870. if (BuildAndDiagnose)
  13871. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
  13872. CaptureType, Invalid);
  13873. return !Invalid;
  13874. }
  13875. /// Capture the given variable in the captured region.
  13876. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  13877. VarDecl *Var,
  13878. SourceLocation Loc,
  13879. const bool BuildAndDiagnose,
  13880. QualType &CaptureType,
  13881. QualType &DeclRefType,
  13882. const bool RefersToCapturedVariable,
  13883. Sema &S, bool Invalid) {
  13884. // By default, capture variables by reference.
  13885. bool ByRef = true;
  13886. // Using an LValue reference type is consistent with Lambdas (see below).
  13887. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  13888. if (S.isOpenMPCapturedDecl(Var)) {
  13889. bool HasConst = DeclRefType.isConstQualified();
  13890. DeclRefType = DeclRefType.getUnqualifiedType();
  13891. // Don't lose diagnostics about assignments to const.
  13892. if (HasConst)
  13893. DeclRefType.addConst();
  13894. }
  13895. ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
  13896. RSI->OpenMPCaptureLevel);
  13897. }
  13898. if (ByRef)
  13899. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13900. else
  13901. CaptureType = DeclRefType;
  13902. // Actually capture the variable.
  13903. if (BuildAndDiagnose)
  13904. RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
  13905. Loc, SourceLocation(), CaptureType, Invalid);
  13906. return !Invalid;
  13907. }
  13908. /// Capture the given variable in the lambda.
  13909. static bool captureInLambda(LambdaScopeInfo *LSI,
  13910. VarDecl *Var,
  13911. SourceLocation Loc,
  13912. const bool BuildAndDiagnose,
  13913. QualType &CaptureType,
  13914. QualType &DeclRefType,
  13915. const bool RefersToCapturedVariable,
  13916. const Sema::TryCaptureKind Kind,
  13917. SourceLocation EllipsisLoc,
  13918. const bool IsTopScope,
  13919. Sema &S, bool Invalid) {
  13920. // Determine whether we are capturing by reference or by value.
  13921. bool ByRef = false;
  13922. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  13923. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  13924. } else {
  13925. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  13926. }
  13927. // Compute the type of the field that will capture this variable.
  13928. if (ByRef) {
  13929. // C++11 [expr.prim.lambda]p15:
  13930. // An entity is captured by reference if it is implicitly or
  13931. // explicitly captured but not captured by copy. It is
  13932. // unspecified whether additional unnamed non-static data
  13933. // members are declared in the closure type for entities
  13934. // captured by reference.
  13935. //
  13936. // FIXME: It is not clear whether we want to build an lvalue reference
  13937. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  13938. // to do the former, while EDG does the latter. Core issue 1249 will
  13939. // clarify, but for now we follow GCC because it's a more permissive and
  13940. // easily defensible position.
  13941. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  13942. } else {
  13943. // C++11 [expr.prim.lambda]p14:
  13944. // For each entity captured by copy, an unnamed non-static
  13945. // data member is declared in the closure type. The
  13946. // declaration order of these members is unspecified. The type
  13947. // of such a data member is the type of the corresponding
  13948. // captured entity if the entity is not a reference to an
  13949. // object, or the referenced type otherwise. [Note: If the
  13950. // captured entity is a reference to a function, the
  13951. // corresponding data member is also a reference to a
  13952. // function. - end note ]
  13953. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  13954. if (!RefType->getPointeeType()->isFunctionType())
  13955. CaptureType = RefType->getPointeeType();
  13956. }
  13957. // Forbid the lambda copy-capture of autoreleasing variables.
  13958. if (!Invalid &&
  13959. CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  13960. if (BuildAndDiagnose) {
  13961. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  13962. S.Diag(Var->getLocation(), diag::note_previous_decl)
  13963. << Var->getDeclName();
  13964. Invalid = true;
  13965. } else {
  13966. return false;
  13967. }
  13968. }
  13969. // Make sure that by-copy captures are of a complete and non-abstract type.
  13970. if (!Invalid && BuildAndDiagnose) {
  13971. if (!CaptureType->isDependentType() &&
  13972. S.RequireCompleteType(Loc, CaptureType,
  13973. diag::err_capture_of_incomplete_type,
  13974. Var->getDeclName()))
  13975. Invalid = true;
  13976. else if (S.RequireNonAbstractType(Loc, CaptureType,
  13977. diag::err_capture_of_abstract_type))
  13978. Invalid = true;
  13979. }
  13980. }
  13981. // Compute the type of a reference to this captured variable.
  13982. if (ByRef)
  13983. DeclRefType = CaptureType.getNonReferenceType();
  13984. else {
  13985. // C++ [expr.prim.lambda]p5:
  13986. // The closure type for a lambda-expression has a public inline
  13987. // function call operator [...]. This function call operator is
  13988. // declared const (9.3.1) if and only if the lambda-expression's
  13989. // parameter-declaration-clause is not followed by mutable.
  13990. DeclRefType = CaptureType.getNonReferenceType();
  13991. if (!LSI->Mutable && !CaptureType->isReferenceType())
  13992. DeclRefType.addConst();
  13993. }
  13994. // Add the capture.
  13995. if (BuildAndDiagnose)
  13996. LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
  13997. Loc, EllipsisLoc, CaptureType, Invalid);
  13998. return !Invalid;
  13999. }
  14000. bool Sema::tryCaptureVariable(
  14001. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  14002. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  14003. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  14004. // An init-capture is notionally from the context surrounding its
  14005. // declaration, but its parent DC is the lambda class.
  14006. DeclContext *VarDC = Var->getDeclContext();
  14007. if (Var->isInitCapture())
  14008. VarDC = VarDC->getParent();
  14009. DeclContext *DC = CurContext;
  14010. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  14011. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  14012. // We need to sync up the Declaration Context with the
  14013. // FunctionScopeIndexToStopAt
  14014. if (FunctionScopeIndexToStopAt) {
  14015. unsigned FSIndex = FunctionScopes.size() - 1;
  14016. while (FSIndex != MaxFunctionScopesIndex) {
  14017. DC = getLambdaAwareParentOfDeclContext(DC);
  14018. --FSIndex;
  14019. }
  14020. }
  14021. // If the variable is declared in the current context, there is no need to
  14022. // capture it.
  14023. if (VarDC == DC) return true;
  14024. // Capture global variables if it is required to use private copy of this
  14025. // variable.
  14026. bool IsGlobal = !Var->hasLocalStorage();
  14027. if (IsGlobal &&
  14028. !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
  14029. MaxFunctionScopesIndex)))
  14030. return true;
  14031. Var = Var->getCanonicalDecl();
  14032. // Walk up the stack to determine whether we can capture the variable,
  14033. // performing the "simple" checks that don't depend on type. We stop when
  14034. // we've either hit the declared scope of the variable or find an existing
  14035. // capture of that variable. We start from the innermost capturing-entity
  14036. // (the DC) and ensure that all intervening capturing-entities
  14037. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  14038. // declcontext can either capture the variable or have already captured
  14039. // the variable.
  14040. CaptureType = Var->getType();
  14041. DeclRefType = CaptureType.getNonReferenceType();
  14042. bool Nested = false;
  14043. bool Explicit = (Kind != TryCapture_Implicit);
  14044. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  14045. do {
  14046. // Only block literals, captured statements, and lambda expressions can
  14047. // capture; other scopes don't work.
  14048. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  14049. ExprLoc,
  14050. BuildAndDiagnose,
  14051. *this);
  14052. // We need to check for the parent *first* because, if we *have*
  14053. // private-captured a global variable, we need to recursively capture it in
  14054. // intermediate blocks, lambdas, etc.
  14055. if (!ParentDC) {
  14056. if (IsGlobal) {
  14057. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  14058. break;
  14059. }
  14060. return true;
  14061. }
  14062. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  14063. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  14064. // Check whether we've already captured it.
  14065. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  14066. DeclRefType)) {
  14067. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  14068. break;
  14069. }
  14070. // If we are instantiating a generic lambda call operator body,
  14071. // we do not want to capture new variables. What was captured
  14072. // during either a lambdas transformation or initial parsing
  14073. // should be used.
  14074. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  14075. if (BuildAndDiagnose) {
  14076. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14077. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  14078. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14079. Diag(Var->getLocation(), diag::note_previous_decl)
  14080. << Var->getDeclName();
  14081. Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
  14082. } else
  14083. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  14084. }
  14085. return true;
  14086. }
  14087. // Try to capture variable-length arrays types.
  14088. if (Var->getType()->isVariablyModifiedType()) {
  14089. // We're going to walk down into the type and look for VLA
  14090. // expressions.
  14091. QualType QTy = Var->getType();
  14092. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  14093. QTy = PVD->getOriginalType();
  14094. captureVariablyModifiedType(Context, QTy, CSI);
  14095. }
  14096. if (getLangOpts().OpenMP) {
  14097. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14098. // OpenMP private variables should not be captured in outer scope, so
  14099. // just break here. Similarly, global variables that are captured in a
  14100. // target region should not be captured outside the scope of the region.
  14101. if (RSI->CapRegionKind == CR_OpenMP) {
  14102. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  14103. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  14104. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  14105. // When we detect target captures we are looking from inside the
  14106. // target region, therefore we need to propagate the capture from the
  14107. // enclosing region. Therefore, the capture is not initially nested.
  14108. if (IsTargetCap)
  14109. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  14110. if (IsTargetCap || IsOpenMPPrivateDecl) {
  14111. Nested = !IsTargetCap;
  14112. DeclRefType = DeclRefType.getUnqualifiedType();
  14113. CaptureType = Context.getLValueReferenceType(DeclRefType);
  14114. break;
  14115. }
  14116. }
  14117. }
  14118. }
  14119. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  14120. // No capture-default, and this is not an explicit capture
  14121. // so cannot capture this variable.
  14122. if (BuildAndDiagnose) {
  14123. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  14124. Diag(Var->getLocation(), diag::note_previous_decl)
  14125. << Var->getDeclName();
  14126. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  14127. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
  14128. diag::note_lambda_decl);
  14129. // FIXME: If we error out because an outer lambda can not implicitly
  14130. // capture a variable that an inner lambda explicitly captures, we
  14131. // should have the inner lambda do the explicit capture - because
  14132. // it makes for cleaner diagnostics later. This would purely be done
  14133. // so that the diagnostic does not misleadingly claim that a variable
  14134. // can not be captured by a lambda implicitly even though it is captured
  14135. // explicitly. Suggestion:
  14136. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  14137. // at the function head
  14138. // - cache the StartingDeclContext - this must be a lambda
  14139. // - captureInLambda in the innermost lambda the variable.
  14140. }
  14141. return true;
  14142. }
  14143. FunctionScopesIndex--;
  14144. DC = ParentDC;
  14145. Explicit = false;
  14146. } while (!VarDC->Equals(DC));
  14147. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  14148. // computing the type of the capture at each step, checking type-specific
  14149. // requirements, and adding captures if requested.
  14150. // If the variable had already been captured previously, we start capturing
  14151. // at the lambda nested within that one.
  14152. bool Invalid = false;
  14153. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  14154. ++I) {
  14155. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  14156. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  14157. // certain types of variables (unnamed, variably modified types etc.)
  14158. // so check for eligibility.
  14159. if (!Invalid)
  14160. Invalid =
  14161. !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
  14162. // After encountering an error, if we're actually supposed to capture, keep
  14163. // capturing in nested contexts to suppress any follow-on diagnostics.
  14164. if (Invalid && !BuildAndDiagnose)
  14165. return true;
  14166. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  14167. Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14168. DeclRefType, Nested, *this, Invalid);
  14169. Nested = true;
  14170. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  14171. Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
  14172. CaptureType, DeclRefType, Nested,
  14173. *this, Invalid);
  14174. Nested = true;
  14175. } else {
  14176. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  14177. Invalid =
  14178. !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
  14179. DeclRefType, Nested, Kind, EllipsisLoc,
  14180. /*IsTopScope*/ I == N - 1, *this, Invalid);
  14181. Nested = true;
  14182. }
  14183. if (Invalid && !BuildAndDiagnose)
  14184. return true;
  14185. }
  14186. return Invalid;
  14187. }
  14188. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  14189. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  14190. QualType CaptureType;
  14191. QualType DeclRefType;
  14192. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  14193. /*BuildAndDiagnose=*/true, CaptureType,
  14194. DeclRefType, nullptr);
  14195. }
  14196. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  14197. QualType CaptureType;
  14198. QualType DeclRefType;
  14199. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14200. /*BuildAndDiagnose=*/false, CaptureType,
  14201. DeclRefType, nullptr);
  14202. }
  14203. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  14204. QualType CaptureType;
  14205. QualType DeclRefType;
  14206. // Determine whether we can capture this variable.
  14207. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  14208. /*BuildAndDiagnose=*/false, CaptureType,
  14209. DeclRefType, nullptr))
  14210. return QualType();
  14211. return DeclRefType;
  14212. }
  14213. namespace {
  14214. // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
  14215. // The produced TemplateArgumentListInfo* points to data stored within this
  14216. // object, so should only be used in contexts where the pointer will not be
  14217. // used after the CopiedTemplateArgs object is destroyed.
  14218. class CopiedTemplateArgs {
  14219. bool HasArgs;
  14220. TemplateArgumentListInfo TemplateArgStorage;
  14221. public:
  14222. template<typename RefExpr>
  14223. CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
  14224. if (HasArgs)
  14225. E->copyTemplateArgumentsInto(TemplateArgStorage);
  14226. }
  14227. operator TemplateArgumentListInfo*()
  14228. #ifdef __has_cpp_attribute
  14229. #if __has_cpp_attribute(clang::lifetimebound)
  14230. [[clang::lifetimebound]]
  14231. #endif
  14232. #endif
  14233. {
  14234. return HasArgs ? &TemplateArgStorage : nullptr;
  14235. }
  14236. };
  14237. }
  14238. /// Walk the set of potential results of an expression and mark them all as
  14239. /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
  14240. ///
  14241. /// \return A new expression if we found any potential results, ExprEmpty() if
  14242. /// not, and ExprError() if we diagnosed an error.
  14243. static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
  14244. NonOdrUseReason NOUR) {
  14245. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  14246. // an object that satisfies the requirements for appearing in a
  14247. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  14248. // is immediately applied." This function handles the lvalue-to-rvalue
  14249. // conversion part.
  14250. //
  14251. // If we encounter a node that claims to be an odr-use but shouldn't be, we
  14252. // transform it into the relevant kind of non-odr-use node and rebuild the
  14253. // tree of nodes leading to it.
  14254. //
  14255. // This is a mini-TreeTransform that only transforms a restricted subset of
  14256. // nodes (and only certain operands of them).
  14257. // Rebuild a subexpression.
  14258. auto Rebuild = [&](Expr *Sub) {
  14259. return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
  14260. };
  14261. // Check whether a potential result satisfies the requirements of NOUR.
  14262. auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
  14263. // Any entity other than a VarDecl is always odr-used whenever it's named
  14264. // in a potentially-evaluated expression.
  14265. auto *VD = dyn_cast<VarDecl>(D);
  14266. if (!VD)
  14267. return true;
  14268. // C++2a [basic.def.odr]p4:
  14269. // A variable x whose name appears as a potentially-evalauted expression
  14270. // e is odr-used by e unless
  14271. // -- x is a reference that is usable in constant expressions, or
  14272. // -- x is a variable of non-reference type that is usable in constant
  14273. // expressions and has no mutable subobjects, and e is an element of
  14274. // the set of potential results of an expression of
  14275. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14276. // conversion is applied, or
  14277. // -- x is a variable of non-reference type, and e is an element of the
  14278. // set of potential results of a discarded-value expression to which
  14279. // the lvalue-to-rvalue conversion is not applied
  14280. //
  14281. // We check the first bullet and the "potentially-evaluated" condition in
  14282. // BuildDeclRefExpr. We check the type requirements in the second bullet
  14283. // in CheckLValueToRValueConversionOperand below.
  14284. switch (NOUR) {
  14285. case NOUR_None:
  14286. case NOUR_Unevaluated:
  14287. llvm_unreachable("unexpected non-odr-use-reason");
  14288. case NOUR_Constant:
  14289. // Constant references were handled when they were built.
  14290. if (VD->getType()->isReferenceType())
  14291. return true;
  14292. if (auto *RD = VD->getType()->getAsCXXRecordDecl())
  14293. if (RD->hasMutableFields())
  14294. return true;
  14295. if (!VD->isUsableInConstantExpressions(S.Context))
  14296. return true;
  14297. break;
  14298. case NOUR_Discarded:
  14299. if (VD->getType()->isReferenceType())
  14300. return true;
  14301. break;
  14302. }
  14303. return false;
  14304. };
  14305. // Mark that this expression does not constitute an odr-use.
  14306. auto MarkNotOdrUsed = [&] {
  14307. S.MaybeODRUseExprs.erase(E);
  14308. if (LambdaScopeInfo *LSI = S.getCurLambda())
  14309. LSI->markVariableExprAsNonODRUsed(E);
  14310. };
  14311. // C++2a [basic.def.odr]p2:
  14312. // The set of potential results of an expression e is defined as follows:
  14313. switch (E->getStmtClass()) {
  14314. // -- If e is an id-expression, ...
  14315. case Expr::DeclRefExprClass: {
  14316. auto *DRE = cast<DeclRefExpr>(E);
  14317. if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
  14318. break;
  14319. // Rebuild as a non-odr-use DeclRefExpr.
  14320. MarkNotOdrUsed();
  14321. return DeclRefExpr::Create(
  14322. S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
  14323. DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
  14324. DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
  14325. DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
  14326. }
  14327. case Expr::FunctionParmPackExprClass: {
  14328. auto *FPPE = cast<FunctionParmPackExpr>(E);
  14329. // If any of the declarations in the pack is odr-used, then the expression
  14330. // as a whole constitutes an odr-use.
  14331. for (VarDecl *D : *FPPE)
  14332. if (IsPotentialResultOdrUsed(D))
  14333. return ExprEmpty();
  14334. // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
  14335. // nothing cares about whether we marked this as an odr-use, but it might
  14336. // be useful for non-compiler tools.
  14337. MarkNotOdrUsed();
  14338. break;
  14339. }
  14340. // -- If e is a subscripting operation with an array operand...
  14341. case Expr::ArraySubscriptExprClass: {
  14342. auto *ASE = cast<ArraySubscriptExpr>(E);
  14343. Expr *OldBase = ASE->getBase()->IgnoreImplicit();
  14344. if (!OldBase->getType()->isArrayType())
  14345. break;
  14346. ExprResult Base = Rebuild(OldBase);
  14347. if (!Base.isUsable())
  14348. return Base;
  14349. Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
  14350. Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
  14351. SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
  14352. return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
  14353. ASE->getRBracketLoc());
  14354. }
  14355. case Expr::MemberExprClass: {
  14356. auto *ME = cast<MemberExpr>(E);
  14357. // -- If e is a class member access expression [...] naming a non-static
  14358. // data member...
  14359. if (isa<FieldDecl>(ME->getMemberDecl())) {
  14360. ExprResult Base = Rebuild(ME->getBase());
  14361. if (!Base.isUsable())
  14362. return Base;
  14363. return MemberExpr::Create(
  14364. S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
  14365. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
  14366. ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
  14367. CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
  14368. ME->getObjectKind(), ME->isNonOdrUse());
  14369. }
  14370. if (ME->getMemberDecl()->isCXXInstanceMember())
  14371. break;
  14372. // -- If e is a class member access expression naming a static data member,
  14373. // ...
  14374. if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
  14375. break;
  14376. // Rebuild as a non-odr-use MemberExpr.
  14377. MarkNotOdrUsed();
  14378. return MemberExpr::Create(
  14379. S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
  14380. ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
  14381. ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
  14382. ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
  14383. return ExprEmpty();
  14384. }
  14385. case Expr::BinaryOperatorClass: {
  14386. auto *BO = cast<BinaryOperator>(E);
  14387. Expr *LHS = BO->getLHS();
  14388. Expr *RHS = BO->getRHS();
  14389. // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
  14390. if (BO->getOpcode() == BO_PtrMemD) {
  14391. ExprResult Sub = Rebuild(LHS);
  14392. if (!Sub.isUsable())
  14393. return Sub;
  14394. LHS = Sub.get();
  14395. // -- If e is a comma expression, ...
  14396. } else if (BO->getOpcode() == BO_Comma) {
  14397. ExprResult Sub = Rebuild(RHS);
  14398. if (!Sub.isUsable())
  14399. return Sub;
  14400. RHS = Sub.get();
  14401. } else {
  14402. break;
  14403. }
  14404. return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
  14405. LHS, RHS);
  14406. }
  14407. // -- If e has the form (e1)...
  14408. case Expr::ParenExprClass: {
  14409. auto *PE = cast<ParenExpr>(E);
  14410. ExprResult Sub = Rebuild(PE->getSubExpr());
  14411. if (!Sub.isUsable())
  14412. return Sub;
  14413. return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
  14414. }
  14415. // -- If e is a glvalue conditional expression, ...
  14416. // We don't apply this to a binary conditional operator. FIXME: Should we?
  14417. case Expr::ConditionalOperatorClass: {
  14418. auto *CO = cast<ConditionalOperator>(E);
  14419. ExprResult LHS = Rebuild(CO->getLHS());
  14420. if (LHS.isInvalid())
  14421. return ExprError();
  14422. ExprResult RHS = Rebuild(CO->getRHS());
  14423. if (RHS.isInvalid())
  14424. return ExprError();
  14425. if (!LHS.isUsable() && !RHS.isUsable())
  14426. return ExprEmpty();
  14427. if (!LHS.isUsable())
  14428. LHS = CO->getLHS();
  14429. if (!RHS.isUsable())
  14430. RHS = CO->getRHS();
  14431. return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
  14432. CO->getCond(), LHS.get(), RHS.get());
  14433. }
  14434. // [Clang extension]
  14435. // -- If e has the form __extension__ e1...
  14436. case Expr::UnaryOperatorClass: {
  14437. auto *UO = cast<UnaryOperator>(E);
  14438. if (UO->getOpcode() != UO_Extension)
  14439. break;
  14440. ExprResult Sub = Rebuild(UO->getSubExpr());
  14441. if (!Sub.isUsable())
  14442. return Sub;
  14443. return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
  14444. Sub.get());
  14445. }
  14446. // [Clang extension]
  14447. // -- If e has the form _Generic(...), the set of potential results is the
  14448. // union of the sets of potential results of the associated expressions.
  14449. case Expr::GenericSelectionExprClass: {
  14450. auto *GSE = cast<GenericSelectionExpr>(E);
  14451. SmallVector<Expr *, 4> AssocExprs;
  14452. bool AnyChanged = false;
  14453. for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
  14454. ExprResult AssocExpr = Rebuild(OrigAssocExpr);
  14455. if (AssocExpr.isInvalid())
  14456. return ExprError();
  14457. if (AssocExpr.isUsable()) {
  14458. AssocExprs.push_back(AssocExpr.get());
  14459. AnyChanged = true;
  14460. } else {
  14461. AssocExprs.push_back(OrigAssocExpr);
  14462. }
  14463. }
  14464. return AnyChanged ? S.CreateGenericSelectionExpr(
  14465. GSE->getGenericLoc(), GSE->getDefaultLoc(),
  14466. GSE->getRParenLoc(), GSE->getControllingExpr(),
  14467. GSE->getAssocTypeSourceInfos(), AssocExprs)
  14468. : ExprEmpty();
  14469. }
  14470. // [Clang extension]
  14471. // -- If e has the form __builtin_choose_expr(...), the set of potential
  14472. // results is the union of the sets of potential results of the
  14473. // second and third subexpressions.
  14474. case Expr::ChooseExprClass: {
  14475. auto *CE = cast<ChooseExpr>(E);
  14476. ExprResult LHS = Rebuild(CE->getLHS());
  14477. if (LHS.isInvalid())
  14478. return ExprError();
  14479. ExprResult RHS = Rebuild(CE->getLHS());
  14480. if (RHS.isInvalid())
  14481. return ExprError();
  14482. if (!LHS.get() && !RHS.get())
  14483. return ExprEmpty();
  14484. if (!LHS.isUsable())
  14485. LHS = CE->getLHS();
  14486. if (!RHS.isUsable())
  14487. RHS = CE->getRHS();
  14488. return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
  14489. RHS.get(), CE->getRParenLoc());
  14490. }
  14491. // Step through non-syntactic nodes.
  14492. case Expr::ConstantExprClass: {
  14493. auto *CE = cast<ConstantExpr>(E);
  14494. ExprResult Sub = Rebuild(CE->getSubExpr());
  14495. if (!Sub.isUsable())
  14496. return Sub;
  14497. return ConstantExpr::Create(S.Context, Sub.get());
  14498. }
  14499. // We could mostly rely on the recursive rebuilding to rebuild implicit
  14500. // casts, but not at the top level, so rebuild them here.
  14501. case Expr::ImplicitCastExprClass: {
  14502. auto *ICE = cast<ImplicitCastExpr>(E);
  14503. // Only step through the narrow set of cast kinds we expect to encounter.
  14504. // Anything else suggests we've left the region in which potential results
  14505. // can be found.
  14506. switch (ICE->getCastKind()) {
  14507. case CK_NoOp:
  14508. case CK_DerivedToBase:
  14509. case CK_UncheckedDerivedToBase: {
  14510. ExprResult Sub = Rebuild(ICE->getSubExpr());
  14511. if (!Sub.isUsable())
  14512. return Sub;
  14513. CXXCastPath Path(ICE->path());
  14514. return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
  14515. ICE->getValueKind(), &Path);
  14516. }
  14517. default:
  14518. break;
  14519. }
  14520. break;
  14521. }
  14522. default:
  14523. break;
  14524. }
  14525. // Can't traverse through this node. Nothing to do.
  14526. return ExprEmpty();
  14527. }
  14528. ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
  14529. // C++2a [basic.def.odr]p4:
  14530. // [...] an expression of non-volatile-qualified non-class type to which
  14531. // the lvalue-to-rvalue conversion is applied [...]
  14532. if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
  14533. return E;
  14534. ExprResult Result =
  14535. rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
  14536. if (Result.isInvalid())
  14537. return ExprError();
  14538. return Result.get() ? Result : E;
  14539. }
  14540. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  14541. Res = CorrectDelayedTyposInExpr(Res);
  14542. if (!Res.isUsable())
  14543. return Res;
  14544. // If a constant-expression is a reference to a variable where we delay
  14545. // deciding whether it is an odr-use, just assume we will apply the
  14546. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  14547. // (a non-type template argument), we have special handling anyway.
  14548. return CheckLValueToRValueConversionOperand(Res.get());
  14549. }
  14550. void Sema::CleanupVarDeclMarking() {
  14551. // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
  14552. // call.
  14553. MaybeODRUseExprSet LocalMaybeODRUseExprs;
  14554. std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
  14555. for (Expr *E : LocalMaybeODRUseExprs) {
  14556. if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  14557. MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
  14558. DRE->getLocation(), *this);
  14559. } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
  14560. MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
  14561. *this);
  14562. } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
  14563. for (VarDecl *VD : *FP)
  14564. MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
  14565. } else {
  14566. llvm_unreachable("Unexpected expression");
  14567. }
  14568. }
  14569. assert(MaybeODRUseExprs.empty() &&
  14570. "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
  14571. }
  14572. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  14573. VarDecl *Var, Expr *E) {
  14574. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
  14575. isa<FunctionParmPackExpr>(E)) &&
  14576. "Invalid Expr argument to DoMarkVarDeclReferenced");
  14577. Var->setReferenced();
  14578. if (Var->isInvalidDecl())
  14579. return;
  14580. auto *MSI = Var->getMemberSpecializationInfo();
  14581. TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
  14582. : Var->getTemplateSpecializationKind();
  14583. OdrUseContext OdrUse = isOdrUseContext(SemaRef);
  14584. bool UsableInConstantExpr =
  14585. Var->mightBeUsableInConstantExpressions(SemaRef.Context);
  14586. // C++20 [expr.const]p12:
  14587. // A variable [...] is needed for constant evaluation if it is [...] a
  14588. // variable whose name appears as a potentially constant evaluated
  14589. // expression that is either a contexpr variable or is of non-volatile
  14590. // const-qualified integral type or of reference type
  14591. bool NeededForConstantEvaluation =
  14592. isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
  14593. bool NeedDefinition =
  14594. OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
  14595. VarTemplateSpecializationDecl *VarSpec =
  14596. dyn_cast<VarTemplateSpecializationDecl>(Var);
  14597. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  14598. "Can't instantiate a partial template specialization.");
  14599. // If this might be a member specialization of a static data member, check
  14600. // the specialization is visible. We already did the checks for variable
  14601. // template specializations when we created them.
  14602. if (NeedDefinition && TSK != TSK_Undeclared &&
  14603. !isa<VarTemplateSpecializationDecl>(Var))
  14604. SemaRef.checkSpecializationVisibility(Loc, Var);
  14605. // Perform implicit instantiation of static data members, static data member
  14606. // templates of class templates, and variable template specializations. Delay
  14607. // instantiations of variable templates, except for those that could be used
  14608. // in a constant expression.
  14609. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  14610. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  14611. // instantiation declaration if a variable is usable in a constant
  14612. // expression (among other cases).
  14613. bool TryInstantiating =
  14614. TSK == TSK_ImplicitInstantiation ||
  14615. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  14616. if (TryInstantiating) {
  14617. SourceLocation PointOfInstantiation =
  14618. MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
  14619. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  14620. if (FirstInstantiation) {
  14621. PointOfInstantiation = Loc;
  14622. if (MSI)
  14623. MSI->setPointOfInstantiation(PointOfInstantiation);
  14624. else
  14625. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  14626. }
  14627. bool InstantiationDependent = false;
  14628. bool IsNonDependent =
  14629. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  14630. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  14631. : true;
  14632. // Do not instantiate specializations that are still type-dependent.
  14633. if (IsNonDependent) {
  14634. if (UsableInConstantExpr) {
  14635. // Do not defer instantiations of variables that could be used in a
  14636. // constant expression.
  14637. SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
  14638. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  14639. });
  14640. } else if (FirstInstantiation ||
  14641. isa<VarTemplateSpecializationDecl>(Var)) {
  14642. // FIXME: For a specialization of a variable template, we don't
  14643. // distinguish between "declaration and type implicitly instantiated"
  14644. // and "implicit instantiation of definition requested", so we have
  14645. // no direct way to avoid enqueueing the pending instantiation
  14646. // multiple times.
  14647. SemaRef.PendingInstantiations
  14648. .push_back(std::make_pair(Var, PointOfInstantiation));
  14649. }
  14650. }
  14651. }
  14652. }
  14653. // C++2a [basic.def.odr]p4:
  14654. // A variable x whose name appears as a potentially-evaluated expression e
  14655. // is odr-used by e unless
  14656. // -- x is a reference that is usable in constant expressions
  14657. // -- x is a variable of non-reference type that is usable in constant
  14658. // expressions and has no mutable subobjects [FIXME], and e is an
  14659. // element of the set of potential results of an expression of
  14660. // non-volatile-qualified non-class type to which the lvalue-to-rvalue
  14661. // conversion is applied
  14662. // -- x is a variable of non-reference type, and e is an element of the set
  14663. // of potential results of a discarded-value expression to which the
  14664. // lvalue-to-rvalue conversion is not applied [FIXME]
  14665. //
  14666. // We check the first part of the second bullet here, and
  14667. // Sema::CheckLValueToRValueConversionOperand deals with the second part.
  14668. // FIXME: To get the third bullet right, we need to delay this even for
  14669. // variables that are not usable in constant expressions.
  14670. // If we already know this isn't an odr-use, there's nothing more to do.
  14671. if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
  14672. if (DRE->isNonOdrUse())
  14673. return;
  14674. if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
  14675. if (ME->isNonOdrUse())
  14676. return;
  14677. switch (OdrUse) {
  14678. case OdrUseContext::None:
  14679. assert((!E || isa<FunctionParmPackExpr>(E)) &&
  14680. "missing non-odr-use marking for unevaluated decl ref");
  14681. break;
  14682. case OdrUseContext::FormallyOdrUsed:
  14683. // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
  14684. // behavior.
  14685. break;
  14686. case OdrUseContext::Used:
  14687. // If we might later find that this expression isn't actually an odr-use,
  14688. // delay the marking.
  14689. if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
  14690. SemaRef.MaybeODRUseExprs.insert(E);
  14691. else
  14692. MarkVarDeclODRUsed(Var, Loc, SemaRef);
  14693. break;
  14694. case OdrUseContext::Dependent:
  14695. // If this is a dependent context, we don't need to mark variables as
  14696. // odr-used, but we may still need to track them for lambda capture.
  14697. // FIXME: Do we also need to do this inside dependent typeid expressions
  14698. // (which are modeled as unevaluated at this point)?
  14699. const bool RefersToEnclosingScope =
  14700. (SemaRef.CurContext != Var->getDeclContext() &&
  14701. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  14702. if (RefersToEnclosingScope) {
  14703. LambdaScopeInfo *const LSI =
  14704. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  14705. if (LSI && (!LSI->CallOperator ||
  14706. !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
  14707. // If a variable could potentially be odr-used, defer marking it so
  14708. // until we finish analyzing the full expression for any
  14709. // lvalue-to-rvalue
  14710. // or discarded value conversions that would obviate odr-use.
  14711. // Add it to the list of potential captures that will be analyzed
  14712. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  14713. // unless the variable is a reference that was initialized by a constant
  14714. // expression (this will never need to be captured or odr-used).
  14715. //
  14716. // FIXME: We can simplify this a lot after implementing P0588R1.
  14717. assert(E && "Capture variable should be used in an expression.");
  14718. if (!Var->getType()->isReferenceType() ||
  14719. !Var->isUsableInConstantExpressions(SemaRef.Context))
  14720. LSI->addPotentialCapture(E->IgnoreParens());
  14721. }
  14722. }
  14723. break;
  14724. }
  14725. }
  14726. /// Mark a variable referenced, and check whether it is odr-used
  14727. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  14728. /// used directly for normal expressions referring to VarDecl.
  14729. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  14730. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  14731. }
  14732. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  14733. Decl *D, Expr *E, bool MightBeOdrUse) {
  14734. if (SemaRef.isInOpenMPDeclareTargetContext())
  14735. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  14736. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  14737. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  14738. return;
  14739. }
  14740. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  14741. // If this is a call to a method via a cast, also mark the method in the
  14742. // derived class used in case codegen can devirtualize the call.
  14743. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  14744. if (!ME)
  14745. return;
  14746. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  14747. if (!MD)
  14748. return;
  14749. // Only attempt to devirtualize if this is truly a virtual call.
  14750. bool IsVirtualCall = MD->isVirtual() &&
  14751. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  14752. if (!IsVirtualCall)
  14753. return;
  14754. // If it's possible to devirtualize the call, mark the called function
  14755. // referenced.
  14756. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  14757. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  14758. if (DM)
  14759. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  14760. }
  14761. /// Perform reference-marking and odr-use handling for a DeclRefExpr.
  14762. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  14763. // TODO: update this with DR# once a defect report is filed.
  14764. // C++11 defect. The address of a pure member should not be an ODR use, even
  14765. // if it's a qualified reference.
  14766. bool OdrUse = true;
  14767. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  14768. if (Method->isVirtual() &&
  14769. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  14770. OdrUse = false;
  14771. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  14772. }
  14773. /// Perform reference-marking and odr-use handling for a MemberExpr.
  14774. void Sema::MarkMemberReferenced(MemberExpr *E) {
  14775. // C++11 [basic.def.odr]p2:
  14776. // A non-overloaded function whose name appears as a potentially-evaluated
  14777. // expression or a member of a set of candidate functions, if selected by
  14778. // overload resolution when referred to from a potentially-evaluated
  14779. // expression, is odr-used, unless it is a pure virtual function and its
  14780. // name is not explicitly qualified.
  14781. bool MightBeOdrUse = true;
  14782. if (E->performsVirtualDispatch(getLangOpts())) {
  14783. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  14784. if (Method->isPure())
  14785. MightBeOdrUse = false;
  14786. }
  14787. SourceLocation Loc =
  14788. E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
  14789. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  14790. }
  14791. /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
  14792. void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
  14793. for (VarDecl *VD : *E)
  14794. MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
  14795. }
  14796. /// Perform marking for a reference to an arbitrary declaration. It
  14797. /// marks the declaration referenced, and performs odr-use checking for
  14798. /// functions and variables. This method should not be used when building a
  14799. /// normal expression which refers to a variable.
  14800. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  14801. bool MightBeOdrUse) {
  14802. if (MightBeOdrUse) {
  14803. if (auto *VD = dyn_cast<VarDecl>(D)) {
  14804. MarkVariableReferenced(Loc, VD);
  14805. return;
  14806. }
  14807. }
  14808. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  14809. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  14810. return;
  14811. }
  14812. D->setReferenced();
  14813. }
  14814. namespace {
  14815. // Mark all of the declarations used by a type as referenced.
  14816. // FIXME: Not fully implemented yet! We need to have a better understanding
  14817. // of when we're entering a context we should not recurse into.
  14818. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  14819. // TreeTransforms rebuilding the type in a new context. Rather than
  14820. // duplicating the TreeTransform logic, we should consider reusing it here.
  14821. // Currently that causes problems when rebuilding LambdaExprs.
  14822. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  14823. Sema &S;
  14824. SourceLocation Loc;
  14825. public:
  14826. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  14827. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  14828. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  14829. };
  14830. }
  14831. bool MarkReferencedDecls::TraverseTemplateArgument(
  14832. const TemplateArgument &Arg) {
  14833. {
  14834. // A non-type template argument is a constant-evaluated context.
  14835. EnterExpressionEvaluationContext Evaluated(
  14836. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  14837. if (Arg.getKind() == TemplateArgument::Declaration) {
  14838. if (Decl *D = Arg.getAsDecl())
  14839. S.MarkAnyDeclReferenced(Loc, D, true);
  14840. } else if (Arg.getKind() == TemplateArgument::Expression) {
  14841. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  14842. }
  14843. }
  14844. return Inherited::TraverseTemplateArgument(Arg);
  14845. }
  14846. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  14847. MarkReferencedDecls Marker(*this, Loc);
  14848. Marker.TraverseType(T);
  14849. }
  14850. namespace {
  14851. /// Helper class that marks all of the declarations referenced by
  14852. /// potentially-evaluated subexpressions as "referenced".
  14853. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  14854. Sema &S;
  14855. bool SkipLocalVariables;
  14856. public:
  14857. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  14858. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  14859. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  14860. void VisitDeclRefExpr(DeclRefExpr *E) {
  14861. // If we were asked not to visit local variables, don't.
  14862. if (SkipLocalVariables) {
  14863. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  14864. if (VD->hasLocalStorage())
  14865. return;
  14866. }
  14867. S.MarkDeclRefReferenced(E);
  14868. }
  14869. void VisitMemberExpr(MemberExpr *E) {
  14870. S.MarkMemberReferenced(E);
  14871. Inherited::VisitMemberExpr(E);
  14872. }
  14873. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  14874. S.MarkFunctionReferenced(
  14875. E->getBeginLoc(),
  14876. const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
  14877. Visit(E->getSubExpr());
  14878. }
  14879. void VisitCXXNewExpr(CXXNewExpr *E) {
  14880. if (E->getOperatorNew())
  14881. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
  14882. if (E->getOperatorDelete())
  14883. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14884. Inherited::VisitCXXNewExpr(E);
  14885. }
  14886. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  14887. if (E->getOperatorDelete())
  14888. S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
  14889. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  14890. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  14891. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  14892. S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
  14893. }
  14894. Inherited::VisitCXXDeleteExpr(E);
  14895. }
  14896. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  14897. S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
  14898. Inherited::VisitCXXConstructExpr(E);
  14899. }
  14900. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  14901. Visit(E->getExpr());
  14902. }
  14903. };
  14904. }
  14905. /// Mark any declarations that appear within this expression or any
  14906. /// potentially-evaluated subexpressions as "referenced".
  14907. ///
  14908. /// \param SkipLocalVariables If true, don't mark local variables as
  14909. /// 'referenced'.
  14910. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  14911. bool SkipLocalVariables) {
  14912. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  14913. }
  14914. /// Emit a diagnostic that describes an effect on the run-time behavior
  14915. /// of the program being compiled.
  14916. ///
  14917. /// This routine emits the given diagnostic when the code currently being
  14918. /// type-checked is "potentially evaluated", meaning that there is a
  14919. /// possibility that the code will actually be executable. Code in sizeof()
  14920. /// expressions, code used only during overload resolution, etc., are not
  14921. /// potentially evaluated. This routine will suppress such diagnostics or,
  14922. /// in the absolutely nutty case of potentially potentially evaluated
  14923. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  14924. /// later.
  14925. ///
  14926. /// This routine should be used for all diagnostics that describe the run-time
  14927. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  14928. /// Failure to do so will likely result in spurious diagnostics or failures
  14929. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  14930. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
  14931. const PartialDiagnostic &PD) {
  14932. switch (ExprEvalContexts.back().Context) {
  14933. case ExpressionEvaluationContext::Unevaluated:
  14934. case ExpressionEvaluationContext::UnevaluatedList:
  14935. case ExpressionEvaluationContext::UnevaluatedAbstract:
  14936. case ExpressionEvaluationContext::DiscardedStatement:
  14937. // The argument will never be evaluated, so don't complain.
  14938. break;
  14939. case ExpressionEvaluationContext::ConstantEvaluated:
  14940. // Relevant diagnostics should be produced by constant evaluation.
  14941. break;
  14942. case ExpressionEvaluationContext::PotentiallyEvaluated:
  14943. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  14944. if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
  14945. FunctionScopes.back()->PossiblyUnreachableDiags.
  14946. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
  14947. return true;
  14948. }
  14949. // The initializer of a constexpr variable or of the first declaration of a
  14950. // static data member is not syntactically a constant evaluated constant,
  14951. // but nonetheless is always required to be a constant expression, so we
  14952. // can skip diagnosing.
  14953. // FIXME: Using the mangling context here is a hack.
  14954. if (auto *VD = dyn_cast_or_null<VarDecl>(
  14955. ExprEvalContexts.back().ManglingContextDecl)) {
  14956. if (VD->isConstexpr() ||
  14957. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  14958. break;
  14959. // FIXME: For any other kind of variable, we should build a CFG for its
  14960. // initializer and check whether the context in question is reachable.
  14961. }
  14962. Diag(Loc, PD);
  14963. return true;
  14964. }
  14965. return false;
  14966. }
  14967. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  14968. const PartialDiagnostic &PD) {
  14969. return DiagRuntimeBehavior(
  14970. Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
  14971. }
  14972. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  14973. CallExpr *CE, FunctionDecl *FD) {
  14974. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  14975. return false;
  14976. // If we're inside a decltype's expression, don't check for a valid return
  14977. // type or construct temporaries until we know whether this is the last call.
  14978. if (ExprEvalContexts.back().ExprContext ==
  14979. ExpressionEvaluationContextRecord::EK_Decltype) {
  14980. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  14981. return false;
  14982. }
  14983. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  14984. FunctionDecl *FD;
  14985. CallExpr *CE;
  14986. public:
  14987. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  14988. : FD(FD), CE(CE) { }
  14989. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  14990. if (!FD) {
  14991. S.Diag(Loc, diag::err_call_incomplete_return)
  14992. << T << CE->getSourceRange();
  14993. return;
  14994. }
  14995. S.Diag(Loc, diag::err_call_function_incomplete_return)
  14996. << CE->getSourceRange() << FD->getDeclName() << T;
  14997. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  14998. << FD->getDeclName();
  14999. }
  15000. } Diagnoser(FD, CE);
  15001. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  15002. return true;
  15003. return false;
  15004. }
  15005. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  15006. // will prevent this condition from triggering, which is what we want.
  15007. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  15008. SourceLocation Loc;
  15009. unsigned diagnostic = diag::warn_condition_is_assignment;
  15010. bool IsOrAssign = false;
  15011. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  15012. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  15013. return;
  15014. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  15015. // Greylist some idioms by putting them into a warning subcategory.
  15016. if (ObjCMessageExpr *ME
  15017. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  15018. Selector Sel = ME->getSelector();
  15019. // self = [<foo> init...]
  15020. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  15021. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15022. // <foo> = [<bar> nextObject]
  15023. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  15024. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  15025. }
  15026. Loc = Op->getOperatorLoc();
  15027. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  15028. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  15029. return;
  15030. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  15031. Loc = Op->getOperatorLoc();
  15032. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  15033. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  15034. else {
  15035. // Not an assignment.
  15036. return;
  15037. }
  15038. Diag(Loc, diagnostic) << E->getSourceRange();
  15039. SourceLocation Open = E->getBeginLoc();
  15040. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  15041. Diag(Loc, diag::note_condition_assign_silence)
  15042. << FixItHint::CreateInsertion(Open, "(")
  15043. << FixItHint::CreateInsertion(Close, ")");
  15044. if (IsOrAssign)
  15045. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  15046. << FixItHint::CreateReplacement(Loc, "!=");
  15047. else
  15048. Diag(Loc, diag::note_condition_assign_to_comparison)
  15049. << FixItHint::CreateReplacement(Loc, "==");
  15050. }
  15051. /// Redundant parentheses over an equality comparison can indicate
  15052. /// that the user intended an assignment used as condition.
  15053. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  15054. // Don't warn if the parens came from a macro.
  15055. SourceLocation parenLoc = ParenE->getBeginLoc();
  15056. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  15057. return;
  15058. // Don't warn for dependent expressions.
  15059. if (ParenE->isTypeDependent())
  15060. return;
  15061. Expr *E = ParenE->IgnoreParens();
  15062. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  15063. if (opE->getOpcode() == BO_EQ &&
  15064. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  15065. == Expr::MLV_Valid) {
  15066. SourceLocation Loc = opE->getOperatorLoc();
  15067. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  15068. SourceRange ParenERange = ParenE->getSourceRange();
  15069. Diag(Loc, diag::note_equality_comparison_silence)
  15070. << FixItHint::CreateRemoval(ParenERange.getBegin())
  15071. << FixItHint::CreateRemoval(ParenERange.getEnd());
  15072. Diag(Loc, diag::note_equality_comparison_to_assign)
  15073. << FixItHint::CreateReplacement(Loc, "=");
  15074. }
  15075. }
  15076. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  15077. bool IsConstexpr) {
  15078. DiagnoseAssignmentAsCondition(E);
  15079. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  15080. DiagnoseEqualityWithExtraParens(parenE);
  15081. ExprResult result = CheckPlaceholderExpr(E);
  15082. if (result.isInvalid()) return ExprError();
  15083. E = result.get();
  15084. if (!E->isTypeDependent()) {
  15085. if (getLangOpts().CPlusPlus)
  15086. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  15087. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  15088. if (ERes.isInvalid())
  15089. return ExprError();
  15090. E = ERes.get();
  15091. QualType T = E->getType();
  15092. if (!T->isScalarType()) { // C99 6.8.4.1p1
  15093. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  15094. << T << E->getSourceRange();
  15095. return ExprError();
  15096. }
  15097. CheckBoolLikeConversion(E, Loc);
  15098. }
  15099. return E;
  15100. }
  15101. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  15102. Expr *SubExpr, ConditionKind CK) {
  15103. // Empty conditions are valid in for-statements.
  15104. if (!SubExpr)
  15105. return ConditionResult();
  15106. ExprResult Cond;
  15107. switch (CK) {
  15108. case ConditionKind::Boolean:
  15109. Cond = CheckBooleanCondition(Loc, SubExpr);
  15110. break;
  15111. case ConditionKind::ConstexprIf:
  15112. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  15113. break;
  15114. case ConditionKind::Switch:
  15115. Cond = CheckSwitchCondition(Loc, SubExpr);
  15116. break;
  15117. }
  15118. if (Cond.isInvalid())
  15119. return ConditionError();
  15120. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  15121. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  15122. if (!FullExpr.get())
  15123. return ConditionError();
  15124. return ConditionResult(*this, nullptr, FullExpr,
  15125. CK == ConditionKind::ConstexprIf);
  15126. }
  15127. namespace {
  15128. /// A visitor for rebuilding a call to an __unknown_any expression
  15129. /// to have an appropriate type.
  15130. struct RebuildUnknownAnyFunction
  15131. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  15132. Sema &S;
  15133. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  15134. ExprResult VisitStmt(Stmt *S) {
  15135. llvm_unreachable("unexpected statement!");
  15136. }
  15137. ExprResult VisitExpr(Expr *E) {
  15138. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  15139. << E->getSourceRange();
  15140. return ExprError();
  15141. }
  15142. /// Rebuild an expression which simply semantically wraps another
  15143. /// expression which it shares the type and value kind of.
  15144. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15145. ExprResult SubResult = Visit(E->getSubExpr());
  15146. if (SubResult.isInvalid()) return ExprError();
  15147. Expr *SubExpr = SubResult.get();
  15148. E->setSubExpr(SubExpr);
  15149. E->setType(SubExpr->getType());
  15150. E->setValueKind(SubExpr->getValueKind());
  15151. assert(E->getObjectKind() == OK_Ordinary);
  15152. return E;
  15153. }
  15154. ExprResult VisitParenExpr(ParenExpr *E) {
  15155. return rebuildSugarExpr(E);
  15156. }
  15157. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15158. return rebuildSugarExpr(E);
  15159. }
  15160. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15161. ExprResult SubResult = Visit(E->getSubExpr());
  15162. if (SubResult.isInvalid()) return ExprError();
  15163. Expr *SubExpr = SubResult.get();
  15164. E->setSubExpr(SubExpr);
  15165. E->setType(S.Context.getPointerType(SubExpr->getType()));
  15166. assert(E->getValueKind() == VK_RValue);
  15167. assert(E->getObjectKind() == OK_Ordinary);
  15168. return E;
  15169. }
  15170. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  15171. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  15172. E->setType(VD->getType());
  15173. assert(E->getValueKind() == VK_RValue);
  15174. if (S.getLangOpts().CPlusPlus &&
  15175. !(isa<CXXMethodDecl>(VD) &&
  15176. cast<CXXMethodDecl>(VD)->isInstance()))
  15177. E->setValueKind(VK_LValue);
  15178. return E;
  15179. }
  15180. ExprResult VisitMemberExpr(MemberExpr *E) {
  15181. return resolveDecl(E, E->getMemberDecl());
  15182. }
  15183. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15184. return resolveDecl(E, E->getDecl());
  15185. }
  15186. };
  15187. }
  15188. /// Given a function expression of unknown-any type, try to rebuild it
  15189. /// to have a function type.
  15190. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  15191. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  15192. if (Result.isInvalid()) return ExprError();
  15193. return S.DefaultFunctionArrayConversion(Result.get());
  15194. }
  15195. namespace {
  15196. /// A visitor for rebuilding an expression of type __unknown_anytype
  15197. /// into one which resolves the type directly on the referring
  15198. /// expression. Strict preservation of the original source
  15199. /// structure is not a goal.
  15200. struct RebuildUnknownAnyExpr
  15201. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  15202. Sema &S;
  15203. /// The current destination type.
  15204. QualType DestType;
  15205. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  15206. : S(S), DestType(CastType) {}
  15207. ExprResult VisitStmt(Stmt *S) {
  15208. llvm_unreachable("unexpected statement!");
  15209. }
  15210. ExprResult VisitExpr(Expr *E) {
  15211. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15212. << E->getSourceRange();
  15213. return ExprError();
  15214. }
  15215. ExprResult VisitCallExpr(CallExpr *E);
  15216. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  15217. /// Rebuild an expression which simply semantically wraps another
  15218. /// expression which it shares the type and value kind of.
  15219. template <class T> ExprResult rebuildSugarExpr(T *E) {
  15220. ExprResult SubResult = Visit(E->getSubExpr());
  15221. if (SubResult.isInvalid()) return ExprError();
  15222. Expr *SubExpr = SubResult.get();
  15223. E->setSubExpr(SubExpr);
  15224. E->setType(SubExpr->getType());
  15225. E->setValueKind(SubExpr->getValueKind());
  15226. assert(E->getObjectKind() == OK_Ordinary);
  15227. return E;
  15228. }
  15229. ExprResult VisitParenExpr(ParenExpr *E) {
  15230. return rebuildSugarExpr(E);
  15231. }
  15232. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  15233. return rebuildSugarExpr(E);
  15234. }
  15235. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  15236. const PointerType *Ptr = DestType->getAs<PointerType>();
  15237. if (!Ptr) {
  15238. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  15239. << E->getSourceRange();
  15240. return ExprError();
  15241. }
  15242. if (isa<CallExpr>(E->getSubExpr())) {
  15243. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  15244. << E->getSourceRange();
  15245. return ExprError();
  15246. }
  15247. assert(E->getValueKind() == VK_RValue);
  15248. assert(E->getObjectKind() == OK_Ordinary);
  15249. E->setType(DestType);
  15250. // Build the sub-expression as if it were an object of the pointee type.
  15251. DestType = Ptr->getPointeeType();
  15252. ExprResult SubResult = Visit(E->getSubExpr());
  15253. if (SubResult.isInvalid()) return ExprError();
  15254. E->setSubExpr(SubResult.get());
  15255. return E;
  15256. }
  15257. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  15258. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  15259. ExprResult VisitMemberExpr(MemberExpr *E) {
  15260. return resolveDecl(E, E->getMemberDecl());
  15261. }
  15262. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  15263. return resolveDecl(E, E->getDecl());
  15264. }
  15265. };
  15266. }
  15267. /// Rebuilds a call expression which yielded __unknown_anytype.
  15268. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  15269. Expr *CalleeExpr = E->getCallee();
  15270. enum FnKind {
  15271. FK_MemberFunction,
  15272. FK_FunctionPointer,
  15273. FK_BlockPointer
  15274. };
  15275. FnKind Kind;
  15276. QualType CalleeType = CalleeExpr->getType();
  15277. if (CalleeType == S.Context.BoundMemberTy) {
  15278. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  15279. Kind = FK_MemberFunction;
  15280. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  15281. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  15282. CalleeType = Ptr->getPointeeType();
  15283. Kind = FK_FunctionPointer;
  15284. } else {
  15285. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  15286. Kind = FK_BlockPointer;
  15287. }
  15288. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  15289. // Verify that this is a legal result type of a function.
  15290. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15291. unsigned diagID = diag::err_func_returning_array_function;
  15292. if (Kind == FK_BlockPointer)
  15293. diagID = diag::err_block_returning_array_function;
  15294. S.Diag(E->getExprLoc(), diagID)
  15295. << DestType->isFunctionType() << DestType;
  15296. return ExprError();
  15297. }
  15298. // Otherwise, go ahead and set DestType as the call's result.
  15299. E->setType(DestType.getNonLValueExprType(S.Context));
  15300. E->setValueKind(Expr::getValueKindForType(DestType));
  15301. assert(E->getObjectKind() == OK_Ordinary);
  15302. // Rebuild the function type, replacing the result type with DestType.
  15303. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  15304. if (Proto) {
  15305. // __unknown_anytype(...) is a special case used by the debugger when
  15306. // it has no idea what a function's signature is.
  15307. //
  15308. // We want to build this call essentially under the K&R
  15309. // unprototyped rules, but making a FunctionNoProtoType in C++
  15310. // would foul up all sorts of assumptions. However, we cannot
  15311. // simply pass all arguments as variadic arguments, nor can we
  15312. // portably just call the function under a non-variadic type; see
  15313. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  15314. // However, it turns out that in practice it is generally safe to
  15315. // call a function declared as "A foo(B,C,D);" under the prototype
  15316. // "A foo(B,C,D,...);". The only known exception is with the
  15317. // Windows ABI, where any variadic function is implicitly cdecl
  15318. // regardless of its normal CC. Therefore we change the parameter
  15319. // types to match the types of the arguments.
  15320. //
  15321. // This is a hack, but it is far superior to moving the
  15322. // corresponding target-specific code from IR-gen to Sema/AST.
  15323. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  15324. SmallVector<QualType, 8> ArgTypes;
  15325. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  15326. ArgTypes.reserve(E->getNumArgs());
  15327. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  15328. Expr *Arg = E->getArg(i);
  15329. QualType ArgType = Arg->getType();
  15330. if (E->isLValue()) {
  15331. ArgType = S.Context.getLValueReferenceType(ArgType);
  15332. } else if (E->isXValue()) {
  15333. ArgType = S.Context.getRValueReferenceType(ArgType);
  15334. }
  15335. ArgTypes.push_back(ArgType);
  15336. }
  15337. ParamTypes = ArgTypes;
  15338. }
  15339. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  15340. Proto->getExtProtoInfo());
  15341. } else {
  15342. DestType = S.Context.getFunctionNoProtoType(DestType,
  15343. FnType->getExtInfo());
  15344. }
  15345. // Rebuild the appropriate pointer-to-function type.
  15346. switch (Kind) {
  15347. case FK_MemberFunction:
  15348. // Nothing to do.
  15349. break;
  15350. case FK_FunctionPointer:
  15351. DestType = S.Context.getPointerType(DestType);
  15352. break;
  15353. case FK_BlockPointer:
  15354. DestType = S.Context.getBlockPointerType(DestType);
  15355. break;
  15356. }
  15357. // Finally, we can recurse.
  15358. ExprResult CalleeResult = Visit(CalleeExpr);
  15359. if (!CalleeResult.isUsable()) return ExprError();
  15360. E->setCallee(CalleeResult.get());
  15361. // Bind a temporary if necessary.
  15362. return S.MaybeBindToTemporary(E);
  15363. }
  15364. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  15365. // Verify that this is a legal result type of a call.
  15366. if (DestType->isArrayType() || DestType->isFunctionType()) {
  15367. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  15368. << DestType->isFunctionType() << DestType;
  15369. return ExprError();
  15370. }
  15371. // Rewrite the method result type if available.
  15372. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  15373. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  15374. Method->setReturnType(DestType);
  15375. }
  15376. // Change the type of the message.
  15377. E->setType(DestType.getNonReferenceType());
  15378. E->setValueKind(Expr::getValueKindForType(DestType));
  15379. return S.MaybeBindToTemporary(E);
  15380. }
  15381. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  15382. // The only case we should ever see here is a function-to-pointer decay.
  15383. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  15384. assert(E->getValueKind() == VK_RValue);
  15385. assert(E->getObjectKind() == OK_Ordinary);
  15386. E->setType(DestType);
  15387. // Rebuild the sub-expression as the pointee (function) type.
  15388. DestType = DestType->castAs<PointerType>()->getPointeeType();
  15389. ExprResult Result = Visit(E->getSubExpr());
  15390. if (!Result.isUsable()) return ExprError();
  15391. E->setSubExpr(Result.get());
  15392. return E;
  15393. } else if (E->getCastKind() == CK_LValueToRValue) {
  15394. assert(E->getValueKind() == VK_RValue);
  15395. assert(E->getObjectKind() == OK_Ordinary);
  15396. assert(isa<BlockPointerType>(E->getType()));
  15397. E->setType(DestType);
  15398. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  15399. DestType = S.Context.getLValueReferenceType(DestType);
  15400. ExprResult Result = Visit(E->getSubExpr());
  15401. if (!Result.isUsable()) return ExprError();
  15402. E->setSubExpr(Result.get());
  15403. return E;
  15404. } else {
  15405. llvm_unreachable("Unhandled cast type!");
  15406. }
  15407. }
  15408. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  15409. ExprValueKind ValueKind = VK_LValue;
  15410. QualType Type = DestType;
  15411. // We know how to make this work for certain kinds of decls:
  15412. // - functions
  15413. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  15414. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  15415. DestType = Ptr->getPointeeType();
  15416. ExprResult Result = resolveDecl(E, VD);
  15417. if (Result.isInvalid()) return ExprError();
  15418. return S.ImpCastExprToType(Result.get(), Type,
  15419. CK_FunctionToPointerDecay, VK_RValue);
  15420. }
  15421. if (!Type->isFunctionType()) {
  15422. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  15423. << VD << E->getSourceRange();
  15424. return ExprError();
  15425. }
  15426. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  15427. // We must match the FunctionDecl's type to the hack introduced in
  15428. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  15429. // type. See the lengthy commentary in that routine.
  15430. QualType FDT = FD->getType();
  15431. const FunctionType *FnType = FDT->castAs<FunctionType>();
  15432. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  15433. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  15434. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  15435. SourceLocation Loc = FD->getLocation();
  15436. FunctionDecl *NewFD = FunctionDecl::Create(
  15437. S.Context, FD->getDeclContext(), Loc, Loc,
  15438. FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
  15439. SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
  15440. /*ConstexprKind*/ CSK_unspecified);
  15441. if (FD->getQualifier())
  15442. NewFD->setQualifierInfo(FD->getQualifierLoc());
  15443. SmallVector<ParmVarDecl*, 16> Params;
  15444. for (const auto &AI : FT->param_types()) {
  15445. ParmVarDecl *Param =
  15446. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  15447. Param->setScopeInfo(0, Params.size());
  15448. Params.push_back(Param);
  15449. }
  15450. NewFD->setParams(Params);
  15451. DRE->setDecl(NewFD);
  15452. VD = DRE->getDecl();
  15453. }
  15454. }
  15455. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  15456. if (MD->isInstance()) {
  15457. ValueKind = VK_RValue;
  15458. Type = S.Context.BoundMemberTy;
  15459. }
  15460. // Function references aren't l-values in C.
  15461. if (!S.getLangOpts().CPlusPlus)
  15462. ValueKind = VK_RValue;
  15463. // - variables
  15464. } else if (isa<VarDecl>(VD)) {
  15465. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  15466. Type = RefTy->getPointeeType();
  15467. } else if (Type->isFunctionType()) {
  15468. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  15469. << VD << E->getSourceRange();
  15470. return ExprError();
  15471. }
  15472. // - nothing else
  15473. } else {
  15474. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  15475. << VD << E->getSourceRange();
  15476. return ExprError();
  15477. }
  15478. // Modifying the declaration like this is friendly to IR-gen but
  15479. // also really dangerous.
  15480. VD->setType(DestType);
  15481. E->setType(Type);
  15482. E->setValueKind(ValueKind);
  15483. return E;
  15484. }
  15485. /// Check a cast of an unknown-any type. We intentionally only
  15486. /// trigger this for C-style casts.
  15487. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  15488. Expr *CastExpr, CastKind &CastKind,
  15489. ExprValueKind &VK, CXXCastPath &Path) {
  15490. // The type we're casting to must be either void or complete.
  15491. if (!CastType->isVoidType() &&
  15492. RequireCompleteType(TypeRange.getBegin(), CastType,
  15493. diag::err_typecheck_cast_to_incomplete))
  15494. return ExprError();
  15495. // Rewrite the casted expression from scratch.
  15496. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  15497. if (!result.isUsable()) return ExprError();
  15498. CastExpr = result.get();
  15499. VK = CastExpr->getValueKind();
  15500. CastKind = CK_NoOp;
  15501. return CastExpr;
  15502. }
  15503. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  15504. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  15505. }
  15506. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  15507. Expr *arg, QualType &paramType) {
  15508. // If the syntactic form of the argument is not an explicit cast of
  15509. // any sort, just do default argument promotion.
  15510. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  15511. if (!castArg) {
  15512. ExprResult result = DefaultArgumentPromotion(arg);
  15513. if (result.isInvalid()) return ExprError();
  15514. paramType = result.get()->getType();
  15515. return result;
  15516. }
  15517. // Otherwise, use the type that was written in the explicit cast.
  15518. assert(!arg->hasPlaceholderType());
  15519. paramType = castArg->getTypeAsWritten();
  15520. // Copy-initialize a parameter of that type.
  15521. InitializedEntity entity =
  15522. InitializedEntity::InitializeParameter(Context, paramType,
  15523. /*consumed*/ false);
  15524. return PerformCopyInitialization(entity, callLoc, arg);
  15525. }
  15526. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  15527. Expr *orig = E;
  15528. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  15529. while (true) {
  15530. E = E->IgnoreParenImpCasts();
  15531. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  15532. E = call->getCallee();
  15533. diagID = diag::err_uncasted_call_of_unknown_any;
  15534. } else {
  15535. break;
  15536. }
  15537. }
  15538. SourceLocation loc;
  15539. NamedDecl *d;
  15540. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  15541. loc = ref->getLocation();
  15542. d = ref->getDecl();
  15543. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  15544. loc = mem->getMemberLoc();
  15545. d = mem->getMemberDecl();
  15546. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  15547. diagID = diag::err_uncasted_call_of_unknown_any;
  15548. loc = msg->getSelectorStartLoc();
  15549. d = msg->getMethodDecl();
  15550. if (!d) {
  15551. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  15552. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  15553. << orig->getSourceRange();
  15554. return ExprError();
  15555. }
  15556. } else {
  15557. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  15558. << E->getSourceRange();
  15559. return ExprError();
  15560. }
  15561. S.Diag(loc, diagID) << d << orig->getSourceRange();
  15562. // Never recoverable.
  15563. return ExprError();
  15564. }
  15565. /// Check for operands with placeholder types and complain if found.
  15566. /// Returns ExprError() if there was an error and no recovery was possible.
  15567. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  15568. if (!getLangOpts().CPlusPlus) {
  15569. // C cannot handle TypoExpr nodes on either side of a binop because it
  15570. // doesn't handle dependent types properly, so make sure any TypoExprs have
  15571. // been dealt with before checking the operands.
  15572. ExprResult Result = CorrectDelayedTyposInExpr(E);
  15573. if (!Result.isUsable()) return ExprError();
  15574. E = Result.get();
  15575. }
  15576. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  15577. if (!placeholderType) return E;
  15578. switch (placeholderType->getKind()) {
  15579. // Overloaded expressions.
  15580. case BuiltinType::Overload: {
  15581. // Try to resolve a single function template specialization.
  15582. // This is obligatory.
  15583. ExprResult Result = E;
  15584. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  15585. return Result;
  15586. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  15587. // leaves Result unchanged on failure.
  15588. Result = E;
  15589. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  15590. return Result;
  15591. // If that failed, try to recover with a call.
  15592. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  15593. /*complain*/ true);
  15594. return Result;
  15595. }
  15596. // Bound member functions.
  15597. case BuiltinType::BoundMember: {
  15598. ExprResult result = E;
  15599. const Expr *BME = E->IgnoreParens();
  15600. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  15601. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  15602. if (isa<CXXPseudoDestructorExpr>(BME)) {
  15603. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  15604. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  15605. if (ME->getMemberNameInfo().getName().getNameKind() ==
  15606. DeclarationName::CXXDestructorName)
  15607. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  15608. }
  15609. tryToRecoverWithCall(result, PD,
  15610. /*complain*/ true);
  15611. return result;
  15612. }
  15613. // ARC unbridged casts.
  15614. case BuiltinType::ARCUnbridgedCast: {
  15615. Expr *realCast = stripARCUnbridgedCast(E);
  15616. diagnoseARCUnbridgedCast(realCast);
  15617. return realCast;
  15618. }
  15619. // Expressions of unknown type.
  15620. case BuiltinType::UnknownAny:
  15621. return diagnoseUnknownAnyExpr(*this, E);
  15622. // Pseudo-objects.
  15623. case BuiltinType::PseudoObject:
  15624. return checkPseudoObjectRValue(E);
  15625. case BuiltinType::BuiltinFn: {
  15626. // Accept __noop without parens by implicitly converting it to a call expr.
  15627. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  15628. if (DRE) {
  15629. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  15630. if (FD->getBuiltinID() == Builtin::BI__noop) {
  15631. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  15632. CK_BuiltinFnToFnPtr)
  15633. .get();
  15634. return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
  15635. VK_RValue, SourceLocation());
  15636. }
  15637. }
  15638. Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
  15639. return ExprError();
  15640. }
  15641. // Expressions of unknown type.
  15642. case BuiltinType::OMPArraySection:
  15643. Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
  15644. return ExprError();
  15645. // Everything else should be impossible.
  15646. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  15647. case BuiltinType::Id:
  15648. #include "clang/Basic/OpenCLImageTypes.def"
  15649. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  15650. case BuiltinType::Id:
  15651. #include "clang/Basic/OpenCLExtensionTypes.def"
  15652. #define SVE_TYPE(Name, Id, SingletonId) \
  15653. case BuiltinType::Id:
  15654. #include "clang/Basic/AArch64SVEACLETypes.def"
  15655. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  15656. #define PLACEHOLDER_TYPE(Id, SingletonId)
  15657. #include "clang/AST/BuiltinTypes.def"
  15658. break;
  15659. }
  15660. llvm_unreachable("invalid placeholder type!");
  15661. }
  15662. bool Sema::CheckCaseExpression(Expr *E) {
  15663. if (E->isTypeDependent())
  15664. return true;
  15665. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  15666. return E->getType()->isIntegralOrEnumerationType();
  15667. return false;
  15668. }
  15669. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  15670. ExprResult
  15671. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  15672. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  15673. "Unknown Objective-C Boolean value!");
  15674. QualType BoolT = Context.ObjCBuiltinBoolTy;
  15675. if (!Context.getBOOLDecl()) {
  15676. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  15677. Sema::LookupOrdinaryName);
  15678. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  15679. NamedDecl *ND = Result.getFoundDecl();
  15680. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  15681. Context.setBOOLDecl(TD);
  15682. }
  15683. }
  15684. if (Context.getBOOLDecl())
  15685. BoolT = Context.getBOOLType();
  15686. return new (Context)
  15687. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  15688. }
  15689. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  15690. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  15691. SourceLocation RParen) {
  15692. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  15693. auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
  15694. return Spec.getPlatform() == Platform;
  15695. });
  15696. VersionTuple Version;
  15697. if (Spec != AvailSpecs.end())
  15698. Version = Spec->getVersion();
  15699. // The use of `@available` in the enclosing function should be analyzed to
  15700. // warn when it's used inappropriately (i.e. not if(@available)).
  15701. if (getCurFunctionOrMethodDecl())
  15702. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  15703. else if (getCurBlock() || getCurLambda())
  15704. getCurFunction()->HasPotentialAvailabilityViolations = true;
  15705. return new (Context)
  15706. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  15707. }