SemaExpr.cpp 624 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098
  1. //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for expressions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/EvaluatedExprVisitor.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/ExprOpenMP.h"
  26. #include "clang/AST/RecursiveASTVisitor.h"
  27. #include "clang/AST/TypeLoc.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/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaFixItUtils.h"
  43. #include "clang/Sema/SemaInternal.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/Support/ConvertUTF.h"
  46. using namespace clang;
  47. using namespace sema;
  48. /// \brief Determine whether the use of this declaration is valid, without
  49. /// emitting diagnostics.
  50. bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
  51. // See if this is an auto-typed variable whose initializer we are parsing.
  52. if (ParsingInitForAutoVars.count(D))
  53. return false;
  54. // See if this is a deleted function.
  55. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  56. if (FD->isDeleted())
  57. return false;
  58. // If the function has a deduced return type, and we can't deduce it,
  59. // then we can't use it either.
  60. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  61. DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
  62. return false;
  63. }
  64. // See if this function is unavailable.
  65. if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
  66. cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
  67. return false;
  68. return true;
  69. }
  70. static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
  71. // Warn if this is used but marked unused.
  72. if (const auto *A = D->getAttr<UnusedAttr>()) {
  73. // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
  74. // should diagnose them.
  75. if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
  76. A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
  77. const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
  78. if (DC && !DC->hasAttr<UnusedAttr>())
  79. S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
  80. }
  81. }
  82. }
  83. /// \brief Emit a note explaining that this function is deleted.
  84. void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
  85. assert(Decl->isDeleted());
  86. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
  87. if (Method && Method->isDeleted() && Method->isDefaulted()) {
  88. // If the method was explicitly defaulted, point at that declaration.
  89. if (!Method->isImplicit())
  90. Diag(Decl->getLocation(), diag::note_implicitly_deleted);
  91. // Try to diagnose why this special member function was implicitly
  92. // deleted. This might fail, if that reason no longer applies.
  93. CXXSpecialMember CSM = getSpecialMember(Method);
  94. if (CSM != CXXInvalid)
  95. ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
  96. return;
  97. }
  98. auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
  99. if (Ctor && Ctor->isInheritingConstructor())
  100. return NoteDeletedInheritingConstructor(Ctor);
  101. Diag(Decl->getLocation(), diag::note_availability_specified_here)
  102. << Decl << true;
  103. }
  104. /// \brief Determine whether a FunctionDecl was ever declared with an
  105. /// explicit storage class.
  106. static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
  107. for (auto I : D->redecls()) {
  108. if (I->getStorageClass() != SC_None)
  109. return true;
  110. }
  111. return false;
  112. }
  113. /// \brief Check whether we're in an extern inline function and referring to a
  114. /// variable or function with internal linkage (C11 6.7.4p3).
  115. ///
  116. /// This is only a warning because we used to silently accept this code, but
  117. /// in many cases it will not behave correctly. This is not enabled in C++ mode
  118. /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
  119. /// and so while there may still be user mistakes, most of the time we can't
  120. /// prove that there are errors.
  121. static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
  122. const NamedDecl *D,
  123. SourceLocation Loc) {
  124. // This is disabled under C++; there are too many ways for this to fire in
  125. // contexts where the warning is a false positive, or where it is technically
  126. // correct but benign.
  127. if (S.getLangOpts().CPlusPlus)
  128. return;
  129. // Check if this is an inlined function or method.
  130. FunctionDecl *Current = S.getCurFunctionDecl();
  131. if (!Current)
  132. return;
  133. if (!Current->isInlined())
  134. return;
  135. if (!Current->isExternallyVisible())
  136. return;
  137. // Check if the decl has internal linkage.
  138. if (D->getFormalLinkage() != InternalLinkage)
  139. return;
  140. // Downgrade from ExtWarn to Extension if
  141. // (1) the supposedly external inline function is in the main file,
  142. // and probably won't be included anywhere else.
  143. // (2) the thing we're referencing is a pure function.
  144. // (3) the thing we're referencing is another inline function.
  145. // This last can give us false negatives, but it's better than warning on
  146. // wrappers for simple C library functions.
  147. const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
  148. bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
  149. if (!DowngradeWarning && UsedFn)
  150. DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
  151. S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
  152. : diag::ext_internal_in_extern_inline)
  153. << /*IsVar=*/!UsedFn << D;
  154. S.MaybeSuggestAddingStaticToDecl(Current);
  155. S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
  156. << D;
  157. }
  158. void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
  159. const FunctionDecl *First = Cur->getFirstDecl();
  160. // Suggest "static" on the function, if possible.
  161. if (!hasAnyExplicitStorageClass(First)) {
  162. SourceLocation DeclBegin = First->getSourceRange().getBegin();
  163. Diag(DeclBegin, diag::note_convert_inline_to_static)
  164. << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
  165. }
  166. }
  167. /// \brief Determine whether the use of this declaration is valid, and
  168. /// emit any corresponding diagnostics.
  169. ///
  170. /// This routine diagnoses various problems with referencing
  171. /// declarations that can occur when using a declaration. For example,
  172. /// it might warn if a deprecated or unavailable declaration is being
  173. /// used, or produce an error (and return true) if a C++0x deleted
  174. /// function is being used.
  175. ///
  176. /// \returns true if there was an error (this declaration cannot be
  177. /// referenced), false otherwise.
  178. ///
  179. bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
  180. const ObjCInterfaceDecl *UnknownObjCClass,
  181. bool ObjCPropertyAccess,
  182. bool AvoidPartialAvailabilityChecks) {
  183. if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
  184. // If there were any diagnostics suppressed by template argument deduction,
  185. // emit them now.
  186. auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
  187. if (Pos != SuppressedDiagnostics.end()) {
  188. for (const PartialDiagnosticAt &Suppressed : Pos->second)
  189. Diag(Suppressed.first, Suppressed.second);
  190. // Clear out the list of suppressed diagnostics, so that we don't emit
  191. // them again for this specialization. However, we don't obsolete this
  192. // entry from the table, because we want to avoid ever emitting these
  193. // diagnostics again.
  194. Pos->second.clear();
  195. }
  196. // C++ [basic.start.main]p3:
  197. // The function 'main' shall not be used within a program.
  198. if (cast<FunctionDecl>(D)->isMain())
  199. Diag(Loc, diag::ext_main_used);
  200. }
  201. // See if this is an auto-typed variable whose initializer we are parsing.
  202. if (ParsingInitForAutoVars.count(D)) {
  203. if (isa<BindingDecl>(D)) {
  204. Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
  205. << D->getDeclName();
  206. } else {
  207. Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
  208. << D->getDeclName() << cast<VarDecl>(D)->getType();
  209. }
  210. return true;
  211. }
  212. // See if this is a deleted function.
  213. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  214. if (FD->isDeleted()) {
  215. auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
  216. if (Ctor && Ctor->isInheritingConstructor())
  217. Diag(Loc, diag::err_deleted_inherited_ctor_use)
  218. << Ctor->getParent()
  219. << Ctor->getInheritedConstructor().getConstructor()->getParent();
  220. else
  221. Diag(Loc, diag::err_deleted_function_use);
  222. NoteDeletedFunction(FD);
  223. return true;
  224. }
  225. // If the function has a deduced return type, and we can't deduce it,
  226. // then we can't use it either.
  227. if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
  228. DeduceReturnType(FD, Loc))
  229. return true;
  230. if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
  231. return true;
  232. }
  233. auto getReferencedObjCProp = [](const NamedDecl *D) ->
  234. const ObjCPropertyDecl * {
  235. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  236. return MD->findPropertyDecl();
  237. return nullptr;
  238. };
  239. if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
  240. if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
  241. return true;
  242. } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
  243. return true;
  244. }
  245. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  246. // Only the variables omp_in and omp_out are allowed in the combiner.
  247. // Only the variables omp_priv and omp_orig are allowed in the
  248. // initializer-clause.
  249. auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
  250. if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
  251. isa<VarDecl>(D)) {
  252. Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
  253. << getCurFunction()->HasOMPDeclareReductionCombiner;
  254. Diag(D->getLocation(), diag::note_entity_declared_at) << D;
  255. return true;
  256. }
  257. DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess,
  258. AvoidPartialAvailabilityChecks);
  259. DiagnoseUnusedOfDecl(*this, D, Loc);
  260. diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
  261. return false;
  262. }
  263. /// \brief Retrieve the message suffix that should be added to a
  264. /// diagnostic complaining about the given function being deleted or
  265. /// unavailable.
  266. std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
  267. std::string Message;
  268. if (FD->getAvailability(&Message))
  269. return ": " + Message;
  270. return std::string();
  271. }
  272. /// DiagnoseSentinelCalls - This routine checks whether a call or
  273. /// message-send is to a declaration with the sentinel attribute, and
  274. /// if so, it checks that the requirements of the sentinel are
  275. /// satisfied.
  276. void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
  277. ArrayRef<Expr *> Args) {
  278. const SentinelAttr *attr = D->getAttr<SentinelAttr>();
  279. if (!attr)
  280. return;
  281. // The number of formal parameters of the declaration.
  282. unsigned numFormalParams;
  283. // The kind of declaration. This is also an index into a %select in
  284. // the diagnostic.
  285. enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
  286. if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  287. numFormalParams = MD->param_size();
  288. calleeType = CT_Method;
  289. } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  290. numFormalParams = FD->param_size();
  291. calleeType = CT_Function;
  292. } else if (isa<VarDecl>(D)) {
  293. QualType type = cast<ValueDecl>(D)->getType();
  294. const FunctionType *fn = nullptr;
  295. if (const PointerType *ptr = type->getAs<PointerType>()) {
  296. fn = ptr->getPointeeType()->getAs<FunctionType>();
  297. if (!fn) return;
  298. calleeType = CT_Function;
  299. } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
  300. fn = ptr->getPointeeType()->castAs<FunctionType>();
  301. calleeType = CT_Block;
  302. } else {
  303. return;
  304. }
  305. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
  306. numFormalParams = proto->getNumParams();
  307. } else {
  308. numFormalParams = 0;
  309. }
  310. } else {
  311. return;
  312. }
  313. // "nullPos" is the number of formal parameters at the end which
  314. // effectively count as part of the variadic arguments. This is
  315. // useful if you would prefer to not have *any* formal parameters,
  316. // but the language forces you to have at least one.
  317. unsigned nullPos = attr->getNullPos();
  318. assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
  319. numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
  320. // The number of arguments which should follow the sentinel.
  321. unsigned numArgsAfterSentinel = attr->getSentinel();
  322. // If there aren't enough arguments for all the formal parameters,
  323. // the sentinel, and the args after the sentinel, complain.
  324. if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
  325. Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
  326. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  327. return;
  328. }
  329. // Otherwise, find the sentinel expression.
  330. Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
  331. if (!sentinelExpr) return;
  332. if (sentinelExpr->isValueDependent()) return;
  333. if (Context.isSentinelNullExpr(sentinelExpr)) return;
  334. // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
  335. // or 'NULL' if those are actually defined in the context. Only use
  336. // 'nil' for ObjC methods, where it's much more likely that the
  337. // variadic arguments form a list of object pointers.
  338. SourceLocation MissingNilLoc
  339. = getLocForEndOfToken(sentinelExpr->getLocEnd());
  340. std::string NullValue;
  341. if (calleeType == CT_Method && PP.isMacroDefined("nil"))
  342. NullValue = "nil";
  343. else if (getLangOpts().CPlusPlus11)
  344. NullValue = "nullptr";
  345. else if (PP.isMacroDefined("NULL"))
  346. NullValue = "NULL";
  347. else
  348. NullValue = "(void*) 0";
  349. if (MissingNilLoc.isInvalid())
  350. Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
  351. else
  352. Diag(MissingNilLoc, diag::warn_missing_sentinel)
  353. << int(calleeType)
  354. << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
  355. Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
  356. }
  357. SourceRange Sema::getExprRange(Expr *E) const {
  358. return E ? E->getSourceRange() : SourceRange();
  359. }
  360. //===----------------------------------------------------------------------===//
  361. // Standard Promotions and Conversions
  362. //===----------------------------------------------------------------------===//
  363. /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
  364. ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
  365. // Handle any placeholder expressions which made it here.
  366. if (E->getType()->isPlaceholderType()) {
  367. ExprResult result = CheckPlaceholderExpr(E);
  368. if (result.isInvalid()) return ExprError();
  369. E = result.get();
  370. }
  371. QualType Ty = E->getType();
  372. assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
  373. if (Ty->isFunctionType()) {
  374. if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
  375. if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
  376. if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
  377. return ExprError();
  378. E = ImpCastExprToType(E, Context.getPointerType(Ty),
  379. CK_FunctionToPointerDecay).get();
  380. } else if (Ty->isArrayType()) {
  381. // In C90 mode, arrays only promote to pointers if the array expression is
  382. // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
  383. // type 'array of type' is converted to an expression that has type 'pointer
  384. // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
  385. // that has type 'array of type' ...". The relevant change is "an lvalue"
  386. // (C90) to "an expression" (C99).
  387. //
  388. // C++ 4.2p1:
  389. // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
  390. // T" can be converted to an rvalue of type "pointer to T".
  391. //
  392. if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
  393. E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
  394. CK_ArrayToPointerDecay).get();
  395. }
  396. return E;
  397. }
  398. static void CheckForNullPointerDereference(Sema &S, Expr *E) {
  399. // Check to see if we are dereferencing a null pointer. If so,
  400. // and if not volatile-qualified, this is undefined behavior that the
  401. // optimizer will delete, so warn about it. People sometimes try to use this
  402. // to get a deterministic trap and are surprised by clang's behavior. This
  403. // only handles the pattern "*null", which is a very syntactic check.
  404. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
  405. if (UO->getOpcode() == UO_Deref &&
  406. UO->getSubExpr()->IgnoreParenCasts()->
  407. isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
  408. !UO->getType().isVolatileQualified()) {
  409. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  410. S.PDiag(diag::warn_indirection_through_null)
  411. << UO->getSubExpr()->getSourceRange());
  412. S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
  413. S.PDiag(diag::note_indirection_through_null));
  414. }
  415. }
  416. static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
  417. SourceLocation AssignLoc,
  418. const Expr* RHS) {
  419. const ObjCIvarDecl *IV = OIRE->getDecl();
  420. if (!IV)
  421. return;
  422. DeclarationName MemberName = IV->getDeclName();
  423. IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
  424. if (!Member || !Member->isStr("isa"))
  425. return;
  426. const Expr *Base = OIRE->getBase();
  427. QualType BaseType = Base->getType();
  428. if (OIRE->isArrow())
  429. BaseType = BaseType->getPointeeType();
  430. if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
  431. if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
  432. ObjCInterfaceDecl *ClassDeclared = nullptr;
  433. ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
  434. if (!ClassDeclared->getSuperClass()
  435. && (*ClassDeclared->ivar_begin()) == IV) {
  436. if (RHS) {
  437. NamedDecl *ObjectSetClass =
  438. S.LookupSingleName(S.TUScope,
  439. &S.Context.Idents.get("object_setClass"),
  440. SourceLocation(), S.LookupOrdinaryName);
  441. if (ObjectSetClass) {
  442. SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
  443. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
  444. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
  445. FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
  446. AssignLoc), ",") <<
  447. FixItHint::CreateInsertion(RHSLocEnd, ")");
  448. }
  449. else
  450. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
  451. } else {
  452. NamedDecl *ObjectGetClass =
  453. S.LookupSingleName(S.TUScope,
  454. &S.Context.Idents.get("object_getClass"),
  455. SourceLocation(), S.LookupOrdinaryName);
  456. if (ObjectGetClass)
  457. S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
  458. FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
  459. FixItHint::CreateReplacement(
  460. SourceRange(OIRE->getOpLoc(),
  461. OIRE->getLocEnd()), ")");
  462. else
  463. S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
  464. }
  465. S.Diag(IV->getLocation(), diag::note_ivar_decl);
  466. }
  467. }
  468. }
  469. ExprResult Sema::DefaultLvalueConversion(Expr *E) {
  470. // Handle any placeholder expressions which made it here.
  471. if (E->getType()->isPlaceholderType()) {
  472. ExprResult result = CheckPlaceholderExpr(E);
  473. if (result.isInvalid()) return ExprError();
  474. E = result.get();
  475. }
  476. // C++ [conv.lval]p1:
  477. // A glvalue of a non-function, non-array type T can be
  478. // converted to a prvalue.
  479. if (!E->isGLValue()) return E;
  480. QualType T = E->getType();
  481. assert(!T.isNull() && "r-value conversion on typeless expression?");
  482. // We don't want to throw lvalue-to-rvalue casts on top of
  483. // expressions of certain types in C++.
  484. if (getLangOpts().CPlusPlus &&
  485. (E->getType() == Context.OverloadTy ||
  486. T->isDependentType() ||
  487. T->isRecordType()))
  488. return E;
  489. // The C standard is actually really unclear on this point, and
  490. // DR106 tells us what the result should be but not why. It's
  491. // generally best to say that void types just doesn't undergo
  492. // lvalue-to-rvalue at all. Note that expressions of unqualified
  493. // 'void' type are never l-values, but qualified void can be.
  494. if (T->isVoidType())
  495. return E;
  496. // OpenCL usually rejects direct accesses to values of 'half' type.
  497. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  498. T->isHalfType()) {
  499. Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
  500. << 0 << T;
  501. return ExprError();
  502. }
  503. CheckForNullPointerDereference(*this, E);
  504. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
  505. NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
  506. &Context.Idents.get("object_getClass"),
  507. SourceLocation(), LookupOrdinaryName);
  508. if (ObjectGetClass)
  509. Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
  510. FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
  511. FixItHint::CreateReplacement(
  512. SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
  513. else
  514. Diag(E->getExprLoc(), diag::warn_objc_isa_use);
  515. }
  516. else if (const ObjCIvarRefExpr *OIRE =
  517. dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
  518. DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
  519. // C++ [conv.lval]p1:
  520. // [...] If T is a non-class type, the type of the prvalue is the
  521. // cv-unqualified version of T. Otherwise, the type of the
  522. // rvalue is T.
  523. //
  524. // C99 6.3.2.1p2:
  525. // If the lvalue has qualified type, the value has the unqualified
  526. // version of the type of the lvalue; otherwise, the value has the
  527. // type of the lvalue.
  528. if (T.hasQualifiers())
  529. T = T.getUnqualifiedType();
  530. // Under the MS ABI, lock down the inheritance model now.
  531. if (T->isMemberPointerType() &&
  532. Context.getTargetInfo().getCXXABI().isMicrosoft())
  533. (void)isCompleteType(E->getExprLoc(), T);
  534. UpdateMarkingForLValueToRValue(E);
  535. // Loading a __weak object implicitly retains the value, so we need a cleanup to
  536. // balance that.
  537. if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
  538. Cleanup.setExprNeedsCleanups(true);
  539. ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
  540. nullptr, VK_RValue);
  541. // C11 6.3.2.1p2:
  542. // ... if the lvalue has atomic type, the value has the non-atomic version
  543. // of the type of the lvalue ...
  544. if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
  545. T = Atomic->getValueType().getUnqualifiedType();
  546. Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
  547. nullptr, VK_RValue);
  548. }
  549. return Res;
  550. }
  551. ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
  552. ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
  553. if (Res.isInvalid())
  554. return ExprError();
  555. Res = DefaultLvalueConversion(Res.get());
  556. if (Res.isInvalid())
  557. return ExprError();
  558. return Res;
  559. }
  560. /// CallExprUnaryConversions - a special case of an unary conversion
  561. /// performed on a function designator of a call expression.
  562. ExprResult Sema::CallExprUnaryConversions(Expr *E) {
  563. QualType Ty = E->getType();
  564. ExprResult Res = E;
  565. // Only do implicit cast for a function type, but not for a pointer
  566. // to function type.
  567. if (Ty->isFunctionType()) {
  568. Res = ImpCastExprToType(E, Context.getPointerType(Ty),
  569. CK_FunctionToPointerDecay).get();
  570. if (Res.isInvalid())
  571. return ExprError();
  572. }
  573. Res = DefaultLvalueConversion(Res.get());
  574. if (Res.isInvalid())
  575. return ExprError();
  576. return Res.get();
  577. }
  578. /// UsualUnaryConversions - Performs various conversions that are common to most
  579. /// operators (C99 6.3). The conversions of array and function types are
  580. /// sometimes suppressed. For example, the array->pointer conversion doesn't
  581. /// apply if the array is an argument to the sizeof or address (&) operators.
  582. /// In these instances, this routine should *not* be called.
  583. ExprResult Sema::UsualUnaryConversions(Expr *E) {
  584. // First, convert to an r-value.
  585. ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
  586. if (Res.isInvalid())
  587. return ExprError();
  588. E = Res.get();
  589. QualType Ty = E->getType();
  590. assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
  591. // Half FP have to be promoted to float unless it is natively supported
  592. if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
  593. return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
  594. // Try to perform integral promotions if the object has a theoretically
  595. // promotable type.
  596. if (Ty->isIntegralOrUnscopedEnumerationType()) {
  597. // C99 6.3.1.1p2:
  598. //
  599. // The following may be used in an expression wherever an int or
  600. // unsigned int may be used:
  601. // - an object or expression with an integer type whose integer
  602. // conversion rank is less than or equal to the rank of int
  603. // and unsigned int.
  604. // - A bit-field of type _Bool, int, signed int, or unsigned int.
  605. //
  606. // If an int can represent all values of the original type, the
  607. // value is converted to an int; otherwise, it is converted to an
  608. // unsigned int. These are called the integer promotions. All
  609. // other types are unchanged by the integer promotions.
  610. QualType PTy = Context.isPromotableBitField(E);
  611. if (!PTy.isNull()) {
  612. E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
  613. return E;
  614. }
  615. if (Ty->isPromotableIntegerType()) {
  616. QualType PT = Context.getPromotedIntegerType(Ty);
  617. E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
  618. return E;
  619. }
  620. }
  621. return E;
  622. }
  623. /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
  624. /// do not have a prototype. Arguments that have type float or __fp16
  625. /// are promoted to double. All other argument types are converted by
  626. /// UsualUnaryConversions().
  627. ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
  628. QualType Ty = E->getType();
  629. assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
  630. ExprResult Res = UsualUnaryConversions(E);
  631. if (Res.isInvalid())
  632. return ExprError();
  633. E = Res.get();
  634. // If this is a 'float' or '__fp16' (CVR qualified or typedef)
  635. // promote to double.
  636. // Note that default argument promotion applies only to float (and
  637. // half/fp16); it does not apply to _Float16.
  638. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  639. if (BTy && (BTy->getKind() == BuiltinType::Half ||
  640. BTy->getKind() == BuiltinType::Float)) {
  641. if (getLangOpts().OpenCL &&
  642. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  643. if (BTy->getKind() == BuiltinType::Half) {
  644. E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
  645. }
  646. } else {
  647. E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
  648. }
  649. }
  650. // C++ performs lvalue-to-rvalue conversion as a default argument
  651. // promotion, even on class types, but note:
  652. // C++11 [conv.lval]p2:
  653. // When an lvalue-to-rvalue conversion occurs in an unevaluated
  654. // operand or a subexpression thereof the value contained in the
  655. // referenced object is not accessed. Otherwise, if the glvalue
  656. // has a class type, the conversion copy-initializes a temporary
  657. // of type T from the glvalue and the result of the conversion
  658. // is a prvalue for the temporary.
  659. // FIXME: add some way to gate this entire thing for correctness in
  660. // potentially potentially evaluated contexts.
  661. if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
  662. ExprResult Temp = PerformCopyInitialization(
  663. InitializedEntity::InitializeTemporary(E->getType()),
  664. E->getExprLoc(), E);
  665. if (Temp.isInvalid())
  666. return ExprError();
  667. E = Temp.get();
  668. }
  669. return E;
  670. }
  671. /// Determine the degree of POD-ness for an expression.
  672. /// Incomplete types are considered POD, since this check can be performed
  673. /// when we're in an unevaluated context.
  674. Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
  675. if (Ty->isIncompleteType()) {
  676. // C++11 [expr.call]p7:
  677. // After these conversions, if the argument does not have arithmetic,
  678. // enumeration, pointer, pointer to member, or class type, the program
  679. // is ill-formed.
  680. //
  681. // Since we've already performed array-to-pointer and function-to-pointer
  682. // decay, the only such type in C++ is cv void. This also handles
  683. // initializer lists as variadic arguments.
  684. if (Ty->isVoidType())
  685. return VAK_Invalid;
  686. if (Ty->isObjCObjectType())
  687. return VAK_Invalid;
  688. return VAK_Valid;
  689. }
  690. if (Ty.isCXX98PODType(Context))
  691. return VAK_Valid;
  692. // C++11 [expr.call]p7:
  693. // Passing a potentially-evaluated argument of class type (Clause 9)
  694. // having a non-trivial copy constructor, a non-trivial move constructor,
  695. // or a non-trivial destructor, with no corresponding parameter,
  696. // is conditionally-supported with implementation-defined semantics.
  697. if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
  698. if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
  699. if (!Record->hasNonTrivialCopyConstructor() &&
  700. !Record->hasNonTrivialMoveConstructor() &&
  701. !Record->hasNonTrivialDestructor())
  702. return VAK_ValidInCXX11;
  703. if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
  704. return VAK_Valid;
  705. if (Ty->isObjCObjectType())
  706. return VAK_Invalid;
  707. if (getLangOpts().MSVCCompat)
  708. return VAK_MSVCUndefined;
  709. // FIXME: In C++11, these cases are conditionally-supported, meaning we're
  710. // permitted to reject them. We should consider doing so.
  711. return VAK_Undefined;
  712. }
  713. void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
  714. // Don't allow one to pass an Objective-C interface to a vararg.
  715. const QualType &Ty = E->getType();
  716. VarArgKind VAK = isValidVarArgType(Ty);
  717. // Complain about passing non-POD types through varargs.
  718. switch (VAK) {
  719. case VAK_ValidInCXX11:
  720. DiagRuntimeBehavior(
  721. E->getLocStart(), nullptr,
  722. PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
  723. << Ty << CT);
  724. // Fall through.
  725. case VAK_Valid:
  726. if (Ty->isRecordType()) {
  727. // This is unlikely to be what the user intended. If the class has a
  728. // 'c_str' member function, the user probably meant to call that.
  729. DiagRuntimeBehavior(E->getLocStart(), nullptr,
  730. PDiag(diag::warn_pass_class_arg_to_vararg)
  731. << Ty << CT << hasCStrMethod(E) << ".c_str()");
  732. }
  733. break;
  734. case VAK_Undefined:
  735. case VAK_MSVCUndefined:
  736. DiagRuntimeBehavior(
  737. E->getLocStart(), nullptr,
  738. PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
  739. << getLangOpts().CPlusPlus11 << Ty << CT);
  740. break;
  741. case VAK_Invalid:
  742. if (Ty->isObjCObjectType())
  743. DiagRuntimeBehavior(
  744. E->getLocStart(), nullptr,
  745. PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
  746. << Ty << CT);
  747. else
  748. Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
  749. << isa<InitListExpr>(E) << Ty << CT;
  750. break;
  751. }
  752. }
  753. /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
  754. /// will create a trap if the resulting type is not a POD type.
  755. ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
  756. FunctionDecl *FDecl) {
  757. if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
  758. // Strip the unbridged-cast placeholder expression off, if applicable.
  759. if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
  760. (CT == VariadicMethod ||
  761. (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
  762. E = stripARCUnbridgedCast(E);
  763. // Otherwise, do normal placeholder checking.
  764. } else {
  765. ExprResult ExprRes = CheckPlaceholderExpr(E);
  766. if (ExprRes.isInvalid())
  767. return ExprError();
  768. E = ExprRes.get();
  769. }
  770. }
  771. ExprResult ExprRes = DefaultArgumentPromotion(E);
  772. if (ExprRes.isInvalid())
  773. return ExprError();
  774. E = ExprRes.get();
  775. // Diagnostics regarding non-POD argument types are
  776. // emitted along with format string checking in Sema::CheckFunctionCall().
  777. if (isValidVarArgType(E->getType()) == VAK_Undefined) {
  778. // Turn this into a trap.
  779. CXXScopeSpec SS;
  780. SourceLocation TemplateKWLoc;
  781. UnqualifiedId Name;
  782. Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
  783. E->getLocStart());
  784. ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
  785. Name, true, false);
  786. if (TrapFn.isInvalid())
  787. return ExprError();
  788. ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
  789. E->getLocStart(), None,
  790. E->getLocEnd());
  791. if (Call.isInvalid())
  792. return ExprError();
  793. ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
  794. Call.get(), E);
  795. if (Comma.isInvalid())
  796. return ExprError();
  797. return Comma.get();
  798. }
  799. if (!getLangOpts().CPlusPlus &&
  800. RequireCompleteType(E->getExprLoc(), E->getType(),
  801. diag::err_call_incomplete_argument))
  802. return ExprError();
  803. return E;
  804. }
  805. /// \brief Converts an integer to complex float type. Helper function of
  806. /// UsualArithmeticConversions()
  807. ///
  808. /// \return false if the integer expression is an integer type and is
  809. /// successfully converted to the complex type.
  810. static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
  811. ExprResult &ComplexExpr,
  812. QualType IntTy,
  813. QualType ComplexTy,
  814. bool SkipCast) {
  815. if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
  816. if (SkipCast) return false;
  817. if (IntTy->isIntegerType()) {
  818. QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
  819. IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
  820. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  821. CK_FloatingRealToComplex);
  822. } else {
  823. assert(IntTy->isComplexIntegerType());
  824. IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
  825. CK_IntegralComplexToFloatingComplex);
  826. }
  827. return false;
  828. }
  829. /// \brief Handle arithmetic conversion with complex types. Helper function of
  830. /// UsualArithmeticConversions()
  831. static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
  832. ExprResult &RHS, QualType LHSType,
  833. QualType RHSType,
  834. bool IsCompAssign) {
  835. // if we have an integer operand, the result is the complex type.
  836. if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
  837. /*skipCast*/false))
  838. return LHSType;
  839. if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
  840. /*skipCast*/IsCompAssign))
  841. return RHSType;
  842. // This handles complex/complex, complex/float, or float/complex.
  843. // When both operands are complex, the shorter operand is converted to the
  844. // type of the longer, and that is the type of the result. This corresponds
  845. // to what is done when combining two real floating-point operands.
  846. // The fun begins when size promotion occur across type domains.
  847. // From H&S 6.3.4: When one operand is complex and the other is a real
  848. // floating-point type, the less precise type is converted, within it's
  849. // real or complex domain, to the precision of the other type. For example,
  850. // when combining a "long double" with a "double _Complex", the
  851. // "double _Complex" is promoted to "long double _Complex".
  852. // Compute the rank of the two types, regardless of whether they are complex.
  853. int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  854. auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
  855. auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
  856. QualType LHSElementType =
  857. LHSComplexType ? LHSComplexType->getElementType() : LHSType;
  858. QualType RHSElementType =
  859. RHSComplexType ? RHSComplexType->getElementType() : RHSType;
  860. QualType ResultType = S.Context.getComplexType(LHSElementType);
  861. if (Order < 0) {
  862. // Promote the precision of the LHS if not an assignment.
  863. ResultType = S.Context.getComplexType(RHSElementType);
  864. if (!IsCompAssign) {
  865. if (LHSComplexType)
  866. LHS =
  867. S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
  868. else
  869. LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
  870. }
  871. } else if (Order > 0) {
  872. // Promote the precision of the RHS.
  873. if (RHSComplexType)
  874. RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
  875. else
  876. RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
  877. }
  878. return ResultType;
  879. }
  880. /// \brief Handle arithmetic conversion from integer to float. Helper function
  881. /// of UsualArithmeticConversions()
  882. static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
  883. ExprResult &IntExpr,
  884. QualType FloatTy, QualType IntTy,
  885. bool ConvertFloat, bool ConvertInt) {
  886. if (IntTy->isIntegerType()) {
  887. if (ConvertInt)
  888. // Convert intExpr to the lhs floating point type.
  889. IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
  890. CK_IntegralToFloating);
  891. return FloatTy;
  892. }
  893. // Convert both sides to the appropriate complex float.
  894. assert(IntTy->isComplexIntegerType());
  895. QualType result = S.Context.getComplexType(FloatTy);
  896. // _Complex int -> _Complex float
  897. if (ConvertInt)
  898. IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
  899. CK_IntegralComplexToFloatingComplex);
  900. // float -> _Complex float
  901. if (ConvertFloat)
  902. FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
  903. CK_FloatingRealToComplex);
  904. return result;
  905. }
  906. /// \brief Handle arithmethic conversion with floating point types. Helper
  907. /// function of UsualArithmeticConversions()
  908. static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
  909. ExprResult &RHS, QualType LHSType,
  910. QualType RHSType, bool IsCompAssign) {
  911. bool LHSFloat = LHSType->isRealFloatingType();
  912. bool RHSFloat = RHSType->isRealFloatingType();
  913. // If we have two real floating types, convert the smaller operand
  914. // to the bigger result.
  915. if (LHSFloat && RHSFloat) {
  916. int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
  917. if (order > 0) {
  918. RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
  919. return LHSType;
  920. }
  921. assert(order < 0 && "illegal float comparison");
  922. if (!IsCompAssign)
  923. LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
  924. return RHSType;
  925. }
  926. if (LHSFloat) {
  927. // Half FP has to be promoted to float unless it is natively supported
  928. if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
  929. LHSType = S.Context.FloatTy;
  930. return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
  931. /*convertFloat=*/!IsCompAssign,
  932. /*convertInt=*/ true);
  933. }
  934. assert(RHSFloat);
  935. return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
  936. /*convertInt=*/ true,
  937. /*convertFloat=*/!IsCompAssign);
  938. }
  939. /// \brief Diagnose attempts to convert between __float128 and long double if
  940. /// there is no support for such conversion. Helper function of
  941. /// UsualArithmeticConversions().
  942. static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
  943. QualType RHSType) {
  944. /* No issue converting if at least one of the types is not a floating point
  945. type or the two types have the same rank.
  946. */
  947. if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
  948. S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
  949. return false;
  950. assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
  951. "The remaining types must be floating point types.");
  952. auto *LHSComplex = LHSType->getAs<ComplexType>();
  953. auto *RHSComplex = RHSType->getAs<ComplexType>();
  954. QualType LHSElemType = LHSComplex ?
  955. LHSComplex->getElementType() : LHSType;
  956. QualType RHSElemType = RHSComplex ?
  957. RHSComplex->getElementType() : RHSType;
  958. // No issue if the two types have the same representation
  959. if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
  960. &S.Context.getFloatTypeSemantics(RHSElemType))
  961. return false;
  962. bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
  963. RHSElemType == S.Context.LongDoubleTy);
  964. Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
  965. RHSElemType == S.Context.Float128Ty);
  966. /* We've handled the situation where __float128 and long double have the same
  967. representation. The only other allowable conversion is if long double is
  968. really just double.
  969. */
  970. return Float128AndLongDouble &&
  971. (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
  972. &llvm::APFloat::IEEEdouble());
  973. }
  974. typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
  975. namespace {
  976. /// These helper callbacks are placed in an anonymous namespace to
  977. /// permit their use as function template parameters.
  978. ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
  979. return S.ImpCastExprToType(op, toType, CK_IntegralCast);
  980. }
  981. ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
  982. return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
  983. CK_IntegralComplexCast);
  984. }
  985. }
  986. /// \brief Handle integer arithmetic conversions. Helper function of
  987. /// UsualArithmeticConversions()
  988. template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
  989. static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
  990. ExprResult &RHS, QualType LHSType,
  991. QualType RHSType, bool IsCompAssign) {
  992. // The rules for this case are in C99 6.3.1.8
  993. int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
  994. bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
  995. bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
  996. if (LHSSigned == RHSSigned) {
  997. // Same signedness; use the higher-ranked type
  998. if (order >= 0) {
  999. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1000. return LHSType;
  1001. } else if (!IsCompAssign)
  1002. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1003. return RHSType;
  1004. } else if (order != (LHSSigned ? 1 : -1)) {
  1005. // The unsigned type has greater than or equal rank to the
  1006. // signed type, so use the unsigned type
  1007. if (RHSSigned) {
  1008. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1009. return LHSType;
  1010. } else if (!IsCompAssign)
  1011. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1012. return RHSType;
  1013. } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
  1014. // The two types are different widths; if we are here, that
  1015. // means the signed type is larger than the unsigned type, so
  1016. // use the signed type.
  1017. if (LHSSigned) {
  1018. RHS = (*doRHSCast)(S, RHS.get(), LHSType);
  1019. return LHSType;
  1020. } else if (!IsCompAssign)
  1021. LHS = (*doLHSCast)(S, LHS.get(), RHSType);
  1022. return RHSType;
  1023. } else {
  1024. // The signed type is higher-ranked than the unsigned type,
  1025. // but isn't actually any bigger (like unsigned int and long
  1026. // on most 32-bit systems). Use the unsigned type corresponding
  1027. // to the signed type.
  1028. QualType result =
  1029. S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
  1030. RHS = (*doRHSCast)(S, RHS.get(), result);
  1031. if (!IsCompAssign)
  1032. LHS = (*doLHSCast)(S, LHS.get(), result);
  1033. return result;
  1034. }
  1035. }
  1036. /// \brief Handle conversions with GCC complex int extension. Helper function
  1037. /// of UsualArithmeticConversions()
  1038. static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
  1039. ExprResult &RHS, QualType LHSType,
  1040. QualType RHSType,
  1041. bool IsCompAssign) {
  1042. const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
  1043. const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
  1044. if (LHSComplexInt && RHSComplexInt) {
  1045. QualType LHSEltType = LHSComplexInt->getElementType();
  1046. QualType RHSEltType = RHSComplexInt->getElementType();
  1047. QualType ScalarType =
  1048. handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
  1049. (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
  1050. return S.Context.getComplexType(ScalarType);
  1051. }
  1052. if (LHSComplexInt) {
  1053. QualType LHSEltType = LHSComplexInt->getElementType();
  1054. QualType ScalarType =
  1055. handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
  1056. (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
  1057. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1058. RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
  1059. CK_IntegralRealToComplex);
  1060. return ComplexType;
  1061. }
  1062. assert(RHSComplexInt);
  1063. QualType RHSEltType = RHSComplexInt->getElementType();
  1064. QualType ScalarType =
  1065. handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
  1066. (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
  1067. QualType ComplexType = S.Context.getComplexType(ScalarType);
  1068. if (!IsCompAssign)
  1069. LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
  1070. CK_IntegralRealToComplex);
  1071. return ComplexType;
  1072. }
  1073. /// UsualArithmeticConversions - Performs various conversions that are common to
  1074. /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
  1075. /// routine returns the first non-arithmetic type found. The client is
  1076. /// responsible for emitting appropriate error diagnostics.
  1077. QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
  1078. bool IsCompAssign) {
  1079. if (!IsCompAssign) {
  1080. LHS = UsualUnaryConversions(LHS.get());
  1081. if (LHS.isInvalid())
  1082. return QualType();
  1083. }
  1084. RHS = UsualUnaryConversions(RHS.get());
  1085. if (RHS.isInvalid())
  1086. return QualType();
  1087. // For conversion purposes, we ignore any qualifiers.
  1088. // For example, "const float" and "float" are equivalent.
  1089. QualType LHSType =
  1090. Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  1091. QualType RHSType =
  1092. Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  1093. // For conversion purposes, we ignore any atomic qualifier on the LHS.
  1094. if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
  1095. LHSType = AtomicLHS->getValueType();
  1096. // If both types are identical, no conversion is needed.
  1097. if (LHSType == RHSType)
  1098. return LHSType;
  1099. // If either side is a non-arithmetic type (e.g. a pointer), we are done.
  1100. // The caller can deal with this (e.g. pointer + int).
  1101. if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
  1102. return QualType();
  1103. // Apply unary and bitfield promotions to the LHS's type.
  1104. QualType LHSUnpromotedType = LHSType;
  1105. if (LHSType->isPromotableIntegerType())
  1106. LHSType = Context.getPromotedIntegerType(LHSType);
  1107. QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
  1108. if (!LHSBitfieldPromoteTy.isNull())
  1109. LHSType = LHSBitfieldPromoteTy;
  1110. if (LHSType != LHSUnpromotedType && !IsCompAssign)
  1111. LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
  1112. // If both types are identical, no conversion is needed.
  1113. if (LHSType == RHSType)
  1114. return LHSType;
  1115. // At this point, we have two different arithmetic types.
  1116. // Diagnose attempts to convert between __float128 and long double where
  1117. // such conversions currently can't be handled.
  1118. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  1119. return QualType();
  1120. // Handle complex types first (C99 6.3.1.8p1).
  1121. if (LHSType->isComplexType() || RHSType->isComplexType())
  1122. return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1123. IsCompAssign);
  1124. // Now handle "real" floating types (i.e. float, double, long double).
  1125. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  1126. return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
  1127. IsCompAssign);
  1128. // Handle GCC complex int extension.
  1129. if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
  1130. return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
  1131. IsCompAssign);
  1132. // Finally, we have two differing integer types.
  1133. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  1134. (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
  1135. }
  1136. //===----------------------------------------------------------------------===//
  1137. // Semantic Analysis for various Expression Types
  1138. //===----------------------------------------------------------------------===//
  1139. ExprResult
  1140. Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
  1141. SourceLocation DefaultLoc,
  1142. SourceLocation RParenLoc,
  1143. Expr *ControllingExpr,
  1144. ArrayRef<ParsedType> ArgTypes,
  1145. ArrayRef<Expr *> ArgExprs) {
  1146. unsigned NumAssocs = ArgTypes.size();
  1147. assert(NumAssocs == ArgExprs.size());
  1148. TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
  1149. for (unsigned i = 0; i < NumAssocs; ++i) {
  1150. if (ArgTypes[i])
  1151. (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
  1152. else
  1153. Types[i] = nullptr;
  1154. }
  1155. ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
  1156. ControllingExpr,
  1157. llvm::makeArrayRef(Types, NumAssocs),
  1158. ArgExprs);
  1159. delete [] Types;
  1160. return ER;
  1161. }
  1162. ExprResult
  1163. Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
  1164. SourceLocation DefaultLoc,
  1165. SourceLocation RParenLoc,
  1166. Expr *ControllingExpr,
  1167. ArrayRef<TypeSourceInfo *> Types,
  1168. ArrayRef<Expr *> Exprs) {
  1169. unsigned NumAssocs = Types.size();
  1170. assert(NumAssocs == Exprs.size());
  1171. // Decay and strip qualifiers for the controlling expression type, and handle
  1172. // placeholder type replacement. See committee discussion from WG14 DR423.
  1173. {
  1174. EnterExpressionEvaluationContext Unevaluated(
  1175. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  1176. ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
  1177. if (R.isInvalid())
  1178. return ExprError();
  1179. ControllingExpr = R.get();
  1180. }
  1181. // The controlling expression is an unevaluated operand, so side effects are
  1182. // likely unintended.
  1183. if (!inTemplateInstantiation() &&
  1184. ControllingExpr->HasSideEffects(Context, false))
  1185. Diag(ControllingExpr->getExprLoc(),
  1186. diag::warn_side_effects_unevaluated_context);
  1187. bool TypeErrorFound = false,
  1188. IsResultDependent = ControllingExpr->isTypeDependent(),
  1189. ContainsUnexpandedParameterPack
  1190. = ControllingExpr->containsUnexpandedParameterPack();
  1191. for (unsigned i = 0; i < NumAssocs; ++i) {
  1192. if (Exprs[i]->containsUnexpandedParameterPack())
  1193. ContainsUnexpandedParameterPack = true;
  1194. if (Types[i]) {
  1195. if (Types[i]->getType()->containsUnexpandedParameterPack())
  1196. ContainsUnexpandedParameterPack = true;
  1197. if (Types[i]->getType()->isDependentType()) {
  1198. IsResultDependent = true;
  1199. } else {
  1200. // C11 6.5.1.1p2 "The type name in a generic association shall specify a
  1201. // complete object type other than a variably modified type."
  1202. unsigned D = 0;
  1203. if (Types[i]->getType()->isIncompleteType())
  1204. D = diag::err_assoc_type_incomplete;
  1205. else if (!Types[i]->getType()->isObjectType())
  1206. D = diag::err_assoc_type_nonobject;
  1207. else if (Types[i]->getType()->isVariablyModifiedType())
  1208. D = diag::err_assoc_type_variably_modified;
  1209. if (D != 0) {
  1210. Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
  1211. << Types[i]->getTypeLoc().getSourceRange()
  1212. << Types[i]->getType();
  1213. TypeErrorFound = true;
  1214. }
  1215. // C11 6.5.1.1p2 "No two generic associations in the same generic
  1216. // selection shall specify compatible types."
  1217. for (unsigned j = i+1; j < NumAssocs; ++j)
  1218. if (Types[j] && !Types[j]->getType()->isDependentType() &&
  1219. Context.typesAreCompatible(Types[i]->getType(),
  1220. Types[j]->getType())) {
  1221. Diag(Types[j]->getTypeLoc().getBeginLoc(),
  1222. diag::err_assoc_compatible_types)
  1223. << Types[j]->getTypeLoc().getSourceRange()
  1224. << Types[j]->getType()
  1225. << Types[i]->getType();
  1226. Diag(Types[i]->getTypeLoc().getBeginLoc(),
  1227. diag::note_compat_assoc)
  1228. << Types[i]->getTypeLoc().getSourceRange()
  1229. << Types[i]->getType();
  1230. TypeErrorFound = true;
  1231. }
  1232. }
  1233. }
  1234. }
  1235. if (TypeErrorFound)
  1236. return ExprError();
  1237. // If we determined that the generic selection is result-dependent, don't
  1238. // try to compute the result expression.
  1239. if (IsResultDependent)
  1240. return new (Context) GenericSelectionExpr(
  1241. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1242. ContainsUnexpandedParameterPack);
  1243. SmallVector<unsigned, 1> CompatIndices;
  1244. unsigned DefaultIndex = -1U;
  1245. for (unsigned i = 0; i < NumAssocs; ++i) {
  1246. if (!Types[i])
  1247. DefaultIndex = i;
  1248. else if (Context.typesAreCompatible(ControllingExpr->getType(),
  1249. Types[i]->getType()))
  1250. CompatIndices.push_back(i);
  1251. }
  1252. // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
  1253. // type compatible with at most one of the types named in its generic
  1254. // association list."
  1255. if (CompatIndices.size() > 1) {
  1256. // We strip parens here because the controlling expression is typically
  1257. // parenthesized in macro definitions.
  1258. ControllingExpr = ControllingExpr->IgnoreParens();
  1259. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
  1260. << ControllingExpr->getSourceRange() << ControllingExpr->getType()
  1261. << (unsigned) CompatIndices.size();
  1262. for (unsigned I : CompatIndices) {
  1263. Diag(Types[I]->getTypeLoc().getBeginLoc(),
  1264. diag::note_compat_assoc)
  1265. << Types[I]->getTypeLoc().getSourceRange()
  1266. << Types[I]->getType();
  1267. }
  1268. return ExprError();
  1269. }
  1270. // C11 6.5.1.1p2 "If a generic selection has no default generic association,
  1271. // its controlling expression shall have type compatible with exactly one of
  1272. // the types named in its generic association list."
  1273. if (DefaultIndex == -1U && CompatIndices.size() == 0) {
  1274. // We strip parens here because the controlling expression is typically
  1275. // parenthesized in macro definitions.
  1276. ControllingExpr = ControllingExpr->IgnoreParens();
  1277. Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
  1278. << ControllingExpr->getSourceRange() << ControllingExpr->getType();
  1279. return ExprError();
  1280. }
  1281. // C11 6.5.1.1p3 "If a generic selection has a generic association with a
  1282. // type name that is compatible with the type of the controlling expression,
  1283. // then the result expression of the generic selection is the expression
  1284. // in that generic association. Otherwise, the result expression of the
  1285. // generic selection is the expression in the default generic association."
  1286. unsigned ResultIndex =
  1287. CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
  1288. return new (Context) GenericSelectionExpr(
  1289. Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
  1290. ContainsUnexpandedParameterPack, ResultIndex);
  1291. }
  1292. /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
  1293. /// location of the token and the offset of the ud-suffix within it.
  1294. static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
  1295. unsigned Offset) {
  1296. return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
  1297. S.getLangOpts());
  1298. }
  1299. /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
  1300. /// the corresponding cooked (non-raw) literal operator, and build a call to it.
  1301. static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
  1302. IdentifierInfo *UDSuffix,
  1303. SourceLocation UDSuffixLoc,
  1304. ArrayRef<Expr*> Args,
  1305. SourceLocation LitEndLoc) {
  1306. assert(Args.size() <= 2 && "too many arguments for literal operator");
  1307. QualType ArgTy[2];
  1308. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  1309. ArgTy[ArgIdx] = Args[ArgIdx]->getType();
  1310. if (ArgTy[ArgIdx]->isArrayType())
  1311. ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
  1312. }
  1313. DeclarationName OpName =
  1314. S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1315. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1316. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1317. LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
  1318. if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
  1319. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1320. /*AllowStringTemplate*/ false,
  1321. /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
  1322. return ExprError();
  1323. return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
  1324. }
  1325. /// ActOnStringLiteral - The specified tokens were lexed as pasted string
  1326. /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
  1327. /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
  1328. /// multiple tokens. However, the common case is that StringToks points to one
  1329. /// string.
  1330. ///
  1331. ExprResult
  1332. Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
  1333. assert(!StringToks.empty() && "Must have at least one string!");
  1334. StringLiteralParser Literal(StringToks, PP);
  1335. if (Literal.hadError)
  1336. return ExprError();
  1337. SmallVector<SourceLocation, 4> StringTokLocs;
  1338. for (const Token &Tok : StringToks)
  1339. StringTokLocs.push_back(Tok.getLocation());
  1340. QualType CharTy = Context.CharTy;
  1341. StringLiteral::StringKind Kind = StringLiteral::Ascii;
  1342. if (Literal.isWide()) {
  1343. CharTy = Context.getWideCharType();
  1344. Kind = StringLiteral::Wide;
  1345. } else if (Literal.isUTF8()) {
  1346. Kind = StringLiteral::UTF8;
  1347. } else if (Literal.isUTF16()) {
  1348. CharTy = Context.Char16Ty;
  1349. Kind = StringLiteral::UTF16;
  1350. } else if (Literal.isUTF32()) {
  1351. CharTy = Context.Char32Ty;
  1352. Kind = StringLiteral::UTF32;
  1353. } else if (Literal.isPascal()) {
  1354. CharTy = Context.UnsignedCharTy;
  1355. }
  1356. QualType CharTyConst = CharTy;
  1357. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  1358. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  1359. CharTyConst.addConst();
  1360. // Get an array type for the string, according to C99 6.4.5. This includes
  1361. // the nul terminator character as well as the string length for pascal
  1362. // strings.
  1363. QualType StrTy = Context.getConstantArrayType(CharTyConst,
  1364. llvm::APInt(32, Literal.GetNumStringChars()+1),
  1365. ArrayType::Normal, 0);
  1366. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  1367. if (getLangOpts().OpenCL) {
  1368. StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
  1369. }
  1370. // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
  1371. StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
  1372. Kind, Literal.Pascal, StrTy,
  1373. &StringTokLocs[0],
  1374. StringTokLocs.size());
  1375. if (Literal.getUDSuffix().empty())
  1376. return Lit;
  1377. // We're building a user-defined literal.
  1378. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  1379. SourceLocation UDSuffixLoc =
  1380. getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
  1381. Literal.getUDSuffixOffset());
  1382. // Make sure we're allowed user-defined literals here.
  1383. if (!UDLScope)
  1384. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
  1385. // C++11 [lex.ext]p5: The literal L is treated as a call of the form
  1386. // operator "" X (str, len)
  1387. QualType SizeType = Context.getSizeType();
  1388. DeclarationName OpName =
  1389. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  1390. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  1391. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  1392. QualType ArgTy[] = {
  1393. Context.getArrayDecayedType(StrTy), SizeType
  1394. };
  1395. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  1396. switch (LookupLiteralOperator(UDLScope, R, ArgTy,
  1397. /*AllowRaw*/ false, /*AllowTemplate*/ false,
  1398. /*AllowStringTemplate*/ true,
  1399. /*DiagnoseMissing*/ true)) {
  1400. case LOLR_Cooked: {
  1401. llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
  1402. IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
  1403. StringTokLocs[0]);
  1404. Expr *Args[] = { Lit, LenArg };
  1405. return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
  1406. }
  1407. case LOLR_StringTemplate: {
  1408. TemplateArgumentListInfo ExplicitArgs;
  1409. unsigned CharBits = Context.getIntWidth(CharTy);
  1410. bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
  1411. llvm::APSInt Value(CharBits, CharIsUnsigned);
  1412. TemplateArgument TypeArg(CharTy);
  1413. TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
  1414. ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
  1415. for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
  1416. Value = Lit->getCodeUnit(I);
  1417. TemplateArgument Arg(Context, Value, CharTy);
  1418. TemplateArgumentLocInfo ArgInfo;
  1419. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  1420. }
  1421. return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
  1422. &ExplicitArgs);
  1423. }
  1424. case LOLR_Raw:
  1425. case LOLR_Template:
  1426. case LOLR_ErrorNoDiagnostic:
  1427. llvm_unreachable("unexpected literal operator lookup result");
  1428. case LOLR_Error:
  1429. return ExprError();
  1430. }
  1431. llvm_unreachable("unexpected literal operator lookup result");
  1432. }
  1433. ExprResult
  1434. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1435. SourceLocation Loc,
  1436. const CXXScopeSpec *SS) {
  1437. DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
  1438. return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
  1439. }
  1440. /// BuildDeclRefExpr - Build an expression that references a
  1441. /// declaration that does not require a closure capture.
  1442. ExprResult
  1443. Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
  1444. const DeclarationNameInfo &NameInfo,
  1445. const CXXScopeSpec *SS, NamedDecl *FoundD,
  1446. const TemplateArgumentListInfo *TemplateArgs) {
  1447. bool RefersToCapturedVariable =
  1448. isa<VarDecl>(D) &&
  1449. NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
  1450. DeclRefExpr *E;
  1451. if (isa<VarTemplateSpecializationDecl>(D)) {
  1452. VarTemplateSpecializationDecl *VarSpec =
  1453. cast<VarTemplateSpecializationDecl>(D);
  1454. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1455. : NestedNameSpecifierLoc(),
  1456. VarSpec->getTemplateKeywordLoc(), D,
  1457. RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
  1458. FoundD, TemplateArgs);
  1459. } else {
  1460. assert(!TemplateArgs && "No template arguments for non-variable"
  1461. " template specialization references");
  1462. E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
  1463. : NestedNameSpecifierLoc(),
  1464. SourceLocation(), D, RefersToCapturedVariable,
  1465. NameInfo, Ty, VK, FoundD);
  1466. }
  1467. MarkDeclRefReferenced(E);
  1468. if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
  1469. Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
  1470. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
  1471. recordUseOfEvaluatedWeak(E);
  1472. FieldDecl *FD = dyn_cast<FieldDecl>(D);
  1473. if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
  1474. FD = IFD->getAnonField();
  1475. if (FD) {
  1476. UnusedPrivateFields.remove(FD);
  1477. // Just in case we're building an illegal pointer-to-member.
  1478. if (FD->isBitField())
  1479. E->setObjectKind(OK_BitField);
  1480. }
  1481. // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
  1482. // designates a bit-field.
  1483. if (auto *BD = dyn_cast<BindingDecl>(D))
  1484. if (auto *BE = BD->getBinding())
  1485. E->setObjectKind(BE->getObjectKind());
  1486. return E;
  1487. }
  1488. /// Decomposes the given name into a DeclarationNameInfo, its location, and
  1489. /// possibly a list of template arguments.
  1490. ///
  1491. /// If this produces template arguments, it is permitted to call
  1492. /// DecomposeTemplateName.
  1493. ///
  1494. /// This actually loses a lot of source location information for
  1495. /// non-standard name kinds; we should consider preserving that in
  1496. /// some way.
  1497. void
  1498. Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
  1499. TemplateArgumentListInfo &Buffer,
  1500. DeclarationNameInfo &NameInfo,
  1501. const TemplateArgumentListInfo *&TemplateArgs) {
  1502. if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
  1503. Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
  1504. Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
  1505. ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
  1506. Id.TemplateId->NumArgs);
  1507. translateTemplateArguments(TemplateArgsPtr, Buffer);
  1508. TemplateName TName = Id.TemplateId->Template.get();
  1509. SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
  1510. NameInfo = Context.getNameForTemplate(TName, TNameLoc);
  1511. TemplateArgs = &Buffer;
  1512. } else {
  1513. NameInfo = GetNameFromUnqualifiedId(Id);
  1514. TemplateArgs = nullptr;
  1515. }
  1516. }
  1517. static void emitEmptyLookupTypoDiagnostic(
  1518. const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
  1519. DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
  1520. unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
  1521. DeclContext *Ctx =
  1522. SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
  1523. if (!TC) {
  1524. // Emit a special diagnostic for failed member lookups.
  1525. // FIXME: computing the declaration context might fail here (?)
  1526. if (Ctx)
  1527. SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
  1528. << SS.getRange();
  1529. else
  1530. SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
  1531. return;
  1532. }
  1533. std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
  1534. bool DroppedSpecifier =
  1535. TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
  1536. unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
  1537. ? diag::note_implicit_param_decl
  1538. : diag::note_previous_decl;
  1539. if (!Ctx)
  1540. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
  1541. SemaRef.PDiag(NoteID));
  1542. else
  1543. SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
  1544. << Typo << Ctx << DroppedSpecifier
  1545. << SS.getRange(),
  1546. SemaRef.PDiag(NoteID));
  1547. }
  1548. /// Diagnose an empty lookup.
  1549. ///
  1550. /// \return false if new lookup candidates were found
  1551. bool
  1552. Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
  1553. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1554. TemplateArgumentListInfo *ExplicitTemplateArgs,
  1555. ArrayRef<Expr *> Args, TypoExpr **Out) {
  1556. DeclarationName Name = R.getLookupName();
  1557. unsigned diagnostic = diag::err_undeclared_var_use;
  1558. unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
  1559. if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
  1560. Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
  1561. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  1562. diagnostic = diag::err_undeclared_use;
  1563. diagnostic_suggest = diag::err_undeclared_use_suggest;
  1564. }
  1565. // If the original lookup was an unqualified lookup, fake an
  1566. // unqualified lookup. This is useful when (for example) the
  1567. // original lookup would not have found something because it was a
  1568. // dependent name.
  1569. DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
  1570. while (DC) {
  1571. if (isa<CXXRecordDecl>(DC)) {
  1572. LookupQualifiedName(R, DC);
  1573. if (!R.empty()) {
  1574. // Don't give errors about ambiguities in this lookup.
  1575. R.suppressDiagnostics();
  1576. // During a default argument instantiation the CurContext points
  1577. // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
  1578. // function parameter list, hence add an explicit check.
  1579. bool isDefaultArgument =
  1580. !CodeSynthesisContexts.empty() &&
  1581. CodeSynthesisContexts.back().Kind ==
  1582. CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
  1583. CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
  1584. bool isInstance = CurMethod &&
  1585. CurMethod->isInstance() &&
  1586. DC == CurMethod->getParent() && !isDefaultArgument;
  1587. // Give a code modification hint to insert 'this->'.
  1588. // TODO: fixit for inserting 'Base<T>::' in the other cases.
  1589. // Actually quite difficult!
  1590. if (getLangOpts().MSVCCompat)
  1591. diagnostic = diag::ext_found_via_dependent_bases_lookup;
  1592. if (isInstance) {
  1593. Diag(R.getNameLoc(), diagnostic) << Name
  1594. << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
  1595. CheckCXXThisCapture(R.getNameLoc());
  1596. } else {
  1597. Diag(R.getNameLoc(), diagnostic) << Name;
  1598. }
  1599. // Do we really want to note all of these?
  1600. for (NamedDecl *D : R)
  1601. Diag(D->getLocation(), diag::note_dependent_var_use);
  1602. // Return true if we are inside a default argument instantiation
  1603. // and the found name refers to an instance member function, otherwise
  1604. // the function calling DiagnoseEmptyLookup will try to create an
  1605. // implicit member call and this is wrong for default argument.
  1606. if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
  1607. Diag(R.getNameLoc(), diag::err_member_call_without_object);
  1608. return true;
  1609. }
  1610. // Tell the callee to try to recover.
  1611. return false;
  1612. }
  1613. R.clear();
  1614. }
  1615. // In Microsoft mode, if we are performing lookup from within a friend
  1616. // function definition declared at class scope then we must set
  1617. // DC to the lexical parent to be able to search into the parent
  1618. // class.
  1619. if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
  1620. cast<FunctionDecl>(DC)->getFriendObjectKind() &&
  1621. DC->getLexicalParent()->isRecord())
  1622. DC = DC->getLexicalParent();
  1623. else
  1624. DC = DC->getParent();
  1625. }
  1626. // We didn't find anything, so try to correct for a typo.
  1627. TypoCorrection Corrected;
  1628. if (S && Out) {
  1629. SourceLocation TypoLoc = R.getNameLoc();
  1630. assert(!ExplicitTemplateArgs &&
  1631. "Diagnosing an empty lookup with explicit template args!");
  1632. *Out = CorrectTypoDelayed(
  1633. R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
  1634. [=](const TypoCorrection &TC) {
  1635. emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
  1636. diagnostic, diagnostic_suggest);
  1637. },
  1638. nullptr, CTK_ErrorRecovery);
  1639. if (*Out)
  1640. return true;
  1641. } else if (S && (Corrected =
  1642. CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
  1643. &SS, std::move(CCC), CTK_ErrorRecovery))) {
  1644. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  1645. bool DroppedSpecifier =
  1646. Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
  1647. R.setLookupName(Corrected.getCorrection());
  1648. bool AcceptableWithRecovery = false;
  1649. bool AcceptableWithoutRecovery = false;
  1650. NamedDecl *ND = Corrected.getFoundDecl();
  1651. if (ND) {
  1652. if (Corrected.isOverloaded()) {
  1653. OverloadCandidateSet OCS(R.getNameLoc(),
  1654. OverloadCandidateSet::CSK_Normal);
  1655. OverloadCandidateSet::iterator Best;
  1656. for (NamedDecl *CD : Corrected) {
  1657. if (FunctionTemplateDecl *FTD =
  1658. dyn_cast<FunctionTemplateDecl>(CD))
  1659. AddTemplateOverloadCandidate(
  1660. FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
  1661. Args, OCS);
  1662. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  1663. if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
  1664. AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
  1665. Args, OCS);
  1666. }
  1667. switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
  1668. case OR_Success:
  1669. ND = Best->FoundDecl;
  1670. Corrected.setCorrectionDecl(ND);
  1671. break;
  1672. default:
  1673. // FIXME: Arbitrarily pick the first declaration for the note.
  1674. Corrected.setCorrectionDecl(ND);
  1675. break;
  1676. }
  1677. }
  1678. R.addDecl(ND);
  1679. if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
  1680. CXXRecordDecl *Record = nullptr;
  1681. if (Corrected.getCorrectionSpecifier()) {
  1682. const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
  1683. Record = Ty->getAsCXXRecordDecl();
  1684. }
  1685. if (!Record)
  1686. Record = cast<CXXRecordDecl>(
  1687. ND->getDeclContext()->getRedeclContext());
  1688. R.setNamingClass(Record);
  1689. }
  1690. auto *UnderlyingND = ND->getUnderlyingDecl();
  1691. AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
  1692. isa<FunctionTemplateDecl>(UnderlyingND);
  1693. // FIXME: If we ended up with a typo for a type name or
  1694. // Objective-C class name, we're in trouble because the parser
  1695. // is in the wrong place to recover. Suggest the typo
  1696. // correction, but don't make it a fix-it since we're not going
  1697. // to recover well anyway.
  1698. AcceptableWithoutRecovery =
  1699. isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
  1700. } else {
  1701. // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
  1702. // because we aren't able to recover.
  1703. AcceptableWithoutRecovery = true;
  1704. }
  1705. if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
  1706. unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
  1707. ? diag::note_implicit_param_decl
  1708. : diag::note_previous_decl;
  1709. if (SS.isEmpty())
  1710. diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
  1711. PDiag(NoteID), AcceptableWithRecovery);
  1712. else
  1713. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
  1714. << Name << computeDeclContext(SS, false)
  1715. << DroppedSpecifier << SS.getRange(),
  1716. PDiag(NoteID), AcceptableWithRecovery);
  1717. // Tell the callee whether to try to recover.
  1718. return !AcceptableWithRecovery;
  1719. }
  1720. }
  1721. R.clear();
  1722. // Emit a special diagnostic for failed member lookups.
  1723. // FIXME: computing the declaration context might fail here (?)
  1724. if (!SS.isEmpty()) {
  1725. Diag(R.getNameLoc(), diag::err_no_member)
  1726. << Name << computeDeclContext(SS, false)
  1727. << SS.getRange();
  1728. return true;
  1729. }
  1730. // Give up, we can't recover.
  1731. Diag(R.getNameLoc(), diagnostic) << Name;
  1732. return true;
  1733. }
  1734. /// In Microsoft mode, if we are inside a template class whose parent class has
  1735. /// dependent base classes, and we can't resolve an unqualified identifier, then
  1736. /// assume the identifier is a member of a dependent base class. We can only
  1737. /// recover successfully in static methods, instance methods, and other contexts
  1738. /// where 'this' is available. This doesn't precisely match MSVC's
  1739. /// instantiation model, but it's close enough.
  1740. static Expr *
  1741. recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
  1742. DeclarationNameInfo &NameInfo,
  1743. SourceLocation TemplateKWLoc,
  1744. const TemplateArgumentListInfo *TemplateArgs) {
  1745. // Only try to recover from lookup into dependent bases in static methods or
  1746. // contexts where 'this' is available.
  1747. QualType ThisType = S.getCurrentThisType();
  1748. const CXXRecordDecl *RD = nullptr;
  1749. if (!ThisType.isNull())
  1750. RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
  1751. else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
  1752. RD = MD->getParent();
  1753. if (!RD || !RD->hasAnyDependentBases())
  1754. return nullptr;
  1755. // Diagnose this as unqualified lookup into a dependent base class. If 'this'
  1756. // is available, suggest inserting 'this->' as a fixit.
  1757. SourceLocation Loc = NameInfo.getLoc();
  1758. auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
  1759. DB << NameInfo.getName() << RD;
  1760. if (!ThisType.isNull()) {
  1761. DB << FixItHint::CreateInsertion(Loc, "this->");
  1762. return CXXDependentScopeMemberExpr::Create(
  1763. Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
  1764. /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
  1765. /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
  1766. }
  1767. // Synthesize a fake NNS that points to the derived class. This will
  1768. // perform name lookup during template instantiation.
  1769. CXXScopeSpec SS;
  1770. auto *NNS =
  1771. NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
  1772. SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
  1773. return DependentScopeDeclRefExpr::Create(
  1774. Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
  1775. TemplateArgs);
  1776. }
  1777. ExprResult
  1778. Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
  1779. SourceLocation TemplateKWLoc, UnqualifiedId &Id,
  1780. bool HasTrailingLParen, bool IsAddressOfOperand,
  1781. std::unique_ptr<CorrectionCandidateCallback> CCC,
  1782. bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
  1783. assert(!(IsAddressOfOperand && HasTrailingLParen) &&
  1784. "cannot be direct & operand and have a trailing lparen");
  1785. if (SS.isInvalid())
  1786. return ExprError();
  1787. TemplateArgumentListInfo TemplateArgsBuffer;
  1788. // Decompose the UnqualifiedId into the following data.
  1789. DeclarationNameInfo NameInfo;
  1790. const TemplateArgumentListInfo *TemplateArgs;
  1791. DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
  1792. DeclarationName Name = NameInfo.getName();
  1793. IdentifierInfo *II = Name.getAsIdentifierInfo();
  1794. SourceLocation NameLoc = NameInfo.getLoc();
  1795. if (II && II->isEditorPlaceholder()) {
  1796. // FIXME: When typed placeholders are supported we can create a typed
  1797. // placeholder expression node.
  1798. return ExprError();
  1799. }
  1800. // C++ [temp.dep.expr]p3:
  1801. // An id-expression is type-dependent if it contains:
  1802. // -- an identifier that was declared with a dependent type,
  1803. // (note: handled after lookup)
  1804. // -- a template-id that is dependent,
  1805. // (note: handled in BuildTemplateIdExpr)
  1806. // -- a conversion-function-id that specifies a dependent type,
  1807. // -- a nested-name-specifier that contains a class-name that
  1808. // names a dependent type.
  1809. // Determine whether this is a member of an unknown specialization;
  1810. // we need to handle these differently.
  1811. bool DependentID = false;
  1812. if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
  1813. Name.getCXXNameType()->isDependentType()) {
  1814. DependentID = true;
  1815. } else if (SS.isSet()) {
  1816. if (DeclContext *DC = computeDeclContext(SS, false)) {
  1817. if (RequireCompleteDeclContext(SS, DC))
  1818. return ExprError();
  1819. } else {
  1820. DependentID = true;
  1821. }
  1822. }
  1823. if (DependentID)
  1824. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1825. IsAddressOfOperand, TemplateArgs);
  1826. // Perform the required lookup.
  1827. LookupResult R(*this, NameInfo,
  1828. (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
  1829. ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
  1830. if (TemplateArgs) {
  1831. // Lookup the template name again to correctly establish the context in
  1832. // which it was found. This is really unfortunate as we already did the
  1833. // lookup to determine that it was a template name in the first place. If
  1834. // this becomes a performance hit, we can work harder to preserve those
  1835. // results until we get here but it's likely not worth it.
  1836. bool MemberOfUnknownSpecialization;
  1837. LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
  1838. MemberOfUnknownSpecialization);
  1839. if (MemberOfUnknownSpecialization ||
  1840. (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
  1841. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1842. IsAddressOfOperand, TemplateArgs);
  1843. } else {
  1844. bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
  1845. LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
  1846. // If the result might be in a dependent base class, this is a dependent
  1847. // id-expression.
  1848. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  1849. return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
  1850. IsAddressOfOperand, TemplateArgs);
  1851. // If this reference is in an Objective-C method, then we need to do
  1852. // some special Objective-C lookup, too.
  1853. if (IvarLookupFollowUp) {
  1854. ExprResult E(LookupInObjCMethod(R, S, II, true));
  1855. if (E.isInvalid())
  1856. return ExprError();
  1857. if (Expr *Ex = E.getAs<Expr>())
  1858. return Ex;
  1859. }
  1860. }
  1861. if (R.isAmbiguous())
  1862. return ExprError();
  1863. // This could be an implicitly declared function reference (legal in C90,
  1864. // extension in C99, forbidden in C++).
  1865. if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
  1866. NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
  1867. if (D) R.addDecl(D);
  1868. }
  1869. // Determine whether this name might be a candidate for
  1870. // argument-dependent lookup.
  1871. bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
  1872. if (R.empty() && !ADL) {
  1873. if (SS.isEmpty() && getLangOpts().MSVCCompat) {
  1874. if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
  1875. TemplateKWLoc, TemplateArgs))
  1876. return E;
  1877. }
  1878. // Don't diagnose an empty lookup for inline assembly.
  1879. if (IsInlineAsmIdentifier)
  1880. return ExprError();
  1881. // If this name wasn't predeclared and if this is not a function
  1882. // call, diagnose the problem.
  1883. TypoExpr *TE = nullptr;
  1884. auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
  1885. II, SS.isValid() ? SS.getScopeRep() : nullptr);
  1886. DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
  1887. assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
  1888. "Typo correction callback misconfigured");
  1889. if (CCC) {
  1890. // Make sure the callback knows what the typo being diagnosed is.
  1891. CCC->setTypoName(II);
  1892. if (SS.isValid())
  1893. CCC->setTypoNNS(SS.getScopeRep());
  1894. }
  1895. if (DiagnoseEmptyLookup(S, SS, R,
  1896. CCC ? std::move(CCC) : std::move(DefaultValidator),
  1897. nullptr, None, &TE)) {
  1898. if (TE && KeywordReplacement) {
  1899. auto &State = getTypoExprState(TE);
  1900. auto BestTC = State.Consumer->getNextCorrection();
  1901. if (BestTC.isKeyword()) {
  1902. auto *II = BestTC.getCorrectionAsIdentifierInfo();
  1903. if (State.DiagHandler)
  1904. State.DiagHandler(BestTC);
  1905. KeywordReplacement->startToken();
  1906. KeywordReplacement->setKind(II->getTokenID());
  1907. KeywordReplacement->setIdentifierInfo(II);
  1908. KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
  1909. // Clean up the state associated with the TypoExpr, since it has
  1910. // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
  1911. clearDelayedTypo(TE);
  1912. // Signal that a correction to a keyword was performed by returning a
  1913. // valid-but-null ExprResult.
  1914. return (Expr*)nullptr;
  1915. }
  1916. State.Consumer->resetCorrectionStream();
  1917. }
  1918. return TE ? TE : ExprError();
  1919. }
  1920. assert(!R.empty() &&
  1921. "DiagnoseEmptyLookup returned false but added no results");
  1922. // If we found an Objective-C instance variable, let
  1923. // LookupInObjCMethod build the appropriate expression to
  1924. // reference the ivar.
  1925. if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
  1926. R.clear();
  1927. ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
  1928. // In a hopelessly buggy code, Objective-C instance variable
  1929. // lookup fails and no expression will be built to reference it.
  1930. if (!E.isInvalid() && !E.get())
  1931. return ExprError();
  1932. return E;
  1933. }
  1934. }
  1935. // This is guaranteed from this point on.
  1936. assert(!R.empty() || ADL);
  1937. // Check whether this might be a C++ implicit instance member access.
  1938. // C++ [class.mfct.non-static]p3:
  1939. // When an id-expression that is not part of a class member access
  1940. // syntax and not used to form a pointer to member is used in the
  1941. // body of a non-static member function of class X, if name lookup
  1942. // resolves the name in the id-expression to a non-static non-type
  1943. // member of some class C, the id-expression is transformed into a
  1944. // class member access expression using (*this) as the
  1945. // postfix-expression to the left of the . operator.
  1946. //
  1947. // But we don't actually need to do this for '&' operands if R
  1948. // resolved to a function or overloaded function set, because the
  1949. // expression is ill-formed if it actually works out to be a
  1950. // non-static member function:
  1951. //
  1952. // C++ [expr.ref]p4:
  1953. // Otherwise, if E1.E2 refers to a non-static member function. . .
  1954. // [t]he expression can be used only as the left-hand operand of a
  1955. // member function call.
  1956. //
  1957. // There are other safeguards against such uses, but it's important
  1958. // to get this right here so that we don't end up making a
  1959. // spuriously dependent expression if we're inside a dependent
  1960. // instance method.
  1961. if (!R.empty() && (*R.begin())->isCXXClassMember()) {
  1962. bool MightBeImplicitMember;
  1963. if (!IsAddressOfOperand)
  1964. MightBeImplicitMember = true;
  1965. else if (!SS.isEmpty())
  1966. MightBeImplicitMember = false;
  1967. else if (R.isOverloadedResult())
  1968. MightBeImplicitMember = false;
  1969. else if (R.isUnresolvableResult())
  1970. MightBeImplicitMember = true;
  1971. else
  1972. MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
  1973. isa<IndirectFieldDecl>(R.getFoundDecl()) ||
  1974. isa<MSPropertyDecl>(R.getFoundDecl());
  1975. if (MightBeImplicitMember)
  1976. return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
  1977. R, TemplateArgs, S);
  1978. }
  1979. if (TemplateArgs || TemplateKWLoc.isValid()) {
  1980. // In C++1y, if this is a variable template id, then check it
  1981. // in BuildTemplateIdExpr().
  1982. // The single lookup result must be a variable template declaration.
  1983. if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
  1984. Id.TemplateId->Kind == TNK_Var_template) {
  1985. assert(R.getAsSingle<VarTemplateDecl>() &&
  1986. "There should only be one declaration found.");
  1987. }
  1988. return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
  1989. }
  1990. return BuildDeclarationNameExpr(SS, R, ADL);
  1991. }
  1992. /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
  1993. /// declaration name, generally during template instantiation.
  1994. /// There's a large number of things which don't need to be done along
  1995. /// this path.
  1996. ExprResult Sema::BuildQualifiedDeclarationNameExpr(
  1997. CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
  1998. bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
  1999. DeclContext *DC = computeDeclContext(SS, false);
  2000. if (!DC)
  2001. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2002. NameInfo, /*TemplateArgs=*/nullptr);
  2003. if (RequireCompleteDeclContext(SS, DC))
  2004. return ExprError();
  2005. LookupResult R(*this, NameInfo, LookupOrdinaryName);
  2006. LookupQualifiedName(R, DC);
  2007. if (R.isAmbiguous())
  2008. return ExprError();
  2009. if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
  2010. return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
  2011. NameInfo, /*TemplateArgs=*/nullptr);
  2012. if (R.empty()) {
  2013. Diag(NameInfo.getLoc(), diag::err_no_member)
  2014. << NameInfo.getName() << DC << SS.getRange();
  2015. return ExprError();
  2016. }
  2017. if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
  2018. // Diagnose a missing typename if this resolved unambiguously to a type in
  2019. // a dependent context. If we can recover with a type, downgrade this to
  2020. // a warning in Microsoft compatibility mode.
  2021. unsigned DiagID = diag::err_typename_missing;
  2022. if (RecoveryTSI && getLangOpts().MSVCCompat)
  2023. DiagID = diag::ext_typename_missing;
  2024. SourceLocation Loc = SS.getBeginLoc();
  2025. auto D = Diag(Loc, DiagID);
  2026. D << SS.getScopeRep() << NameInfo.getName().getAsString()
  2027. << SourceRange(Loc, NameInfo.getEndLoc());
  2028. // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
  2029. // context.
  2030. if (!RecoveryTSI)
  2031. return ExprError();
  2032. // Only issue the fixit if we're prepared to recover.
  2033. D << FixItHint::CreateInsertion(Loc, "typename ");
  2034. // Recover by pretending this was an elaborated type.
  2035. QualType Ty = Context.getTypeDeclType(TD);
  2036. TypeLocBuilder TLB;
  2037. TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
  2038. QualType ET = getElaboratedType(ETK_None, SS, Ty);
  2039. ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
  2040. QTL.setElaboratedKeywordLoc(SourceLocation());
  2041. QTL.setQualifierLoc(SS.getWithLocInContext(Context));
  2042. *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
  2043. return ExprEmpty();
  2044. }
  2045. // Defend against this resolving to an implicit member access. We usually
  2046. // won't get here if this might be a legitimate a class member (we end up in
  2047. // BuildMemberReferenceExpr instead), but this can be valid if we're forming
  2048. // a pointer-to-member or in an unevaluated context in C++11.
  2049. if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
  2050. return BuildPossibleImplicitMemberExpr(SS,
  2051. /*TemplateKWLoc=*/SourceLocation(),
  2052. R, /*TemplateArgs=*/nullptr, S);
  2053. return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
  2054. }
  2055. /// LookupInObjCMethod - The parser has read a name in, and Sema has
  2056. /// detected that we're currently inside an ObjC method. Perform some
  2057. /// additional lookup.
  2058. ///
  2059. /// Ideally, most of this would be done by lookup, but there's
  2060. /// actually quite a lot of extra work involved.
  2061. ///
  2062. /// Returns a null sentinel to indicate trivial success.
  2063. ExprResult
  2064. Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
  2065. IdentifierInfo *II, bool AllowBuiltinCreation) {
  2066. SourceLocation Loc = Lookup.getNameLoc();
  2067. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  2068. // Check for error condition which is already reported.
  2069. if (!CurMethod)
  2070. return ExprError();
  2071. // There are two cases to handle here. 1) scoped lookup could have failed,
  2072. // in which case we should look for an ivar. 2) scoped lookup could have
  2073. // found a decl, but that decl is outside the current instance method (i.e.
  2074. // a global variable). In these two cases, we do a lookup for an ivar with
  2075. // this name, if the lookup sucedes, we replace it our current decl.
  2076. // If we're in a class method, we don't normally want to look for
  2077. // ivars. But if we don't find anything else, and there's an
  2078. // ivar, that's an error.
  2079. bool IsClassMethod = CurMethod->isClassMethod();
  2080. bool LookForIvars;
  2081. if (Lookup.empty())
  2082. LookForIvars = true;
  2083. else if (IsClassMethod)
  2084. LookForIvars = false;
  2085. else
  2086. LookForIvars = (Lookup.isSingleResult() &&
  2087. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
  2088. ObjCInterfaceDecl *IFace = nullptr;
  2089. if (LookForIvars) {
  2090. IFace = CurMethod->getClassInterface();
  2091. ObjCInterfaceDecl *ClassDeclared;
  2092. ObjCIvarDecl *IV = nullptr;
  2093. if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
  2094. // Diagnose using an ivar in a class method.
  2095. if (IsClassMethod)
  2096. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2097. << IV->getDeclName());
  2098. // If we're referencing an invalid decl, just return this as a silent
  2099. // error node. The error diagnostic was already emitted on the decl.
  2100. if (IV->isInvalidDecl())
  2101. return ExprError();
  2102. // Check if referencing a field with __attribute__((deprecated)).
  2103. if (DiagnoseUseOfDecl(IV, Loc))
  2104. return ExprError();
  2105. // Diagnose the use of an ivar outside of the declaring class.
  2106. if (IV->getAccessControl() == ObjCIvarDecl::Private &&
  2107. !declaresSameEntity(ClassDeclared, IFace) &&
  2108. !getLangOpts().DebuggerSupport)
  2109. Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
  2110. // FIXME: This should use a new expr for a direct reference, don't
  2111. // turn this into Self->ivar, just return a BareIVarExpr or something.
  2112. IdentifierInfo &II = Context.Idents.get("self");
  2113. UnqualifiedId SelfName;
  2114. SelfName.setIdentifier(&II, SourceLocation());
  2115. SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
  2116. CXXScopeSpec SelfScopeSpec;
  2117. SourceLocation TemplateKWLoc;
  2118. ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
  2119. SelfName, false, false);
  2120. if (SelfExpr.isInvalid())
  2121. return ExprError();
  2122. SelfExpr = DefaultLvalueConversion(SelfExpr.get());
  2123. if (SelfExpr.isInvalid())
  2124. return ExprError();
  2125. MarkAnyDeclReferenced(Loc, IV, true);
  2126. ObjCMethodFamily MF = CurMethod->getMethodFamily();
  2127. if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
  2128. !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
  2129. Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
  2130. ObjCIvarRefExpr *Result = new (Context)
  2131. ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
  2132. IV->getLocation(), SelfExpr.get(), true, true);
  2133. if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
  2134. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  2135. recordUseOfEvaluatedWeak(Result);
  2136. }
  2137. if (getLangOpts().ObjCAutoRefCount) {
  2138. if (CurContext->isClosure())
  2139. Diag(Loc, diag::warn_implicitly_retains_self)
  2140. << FixItHint::CreateInsertion(Loc, "self->");
  2141. }
  2142. return Result;
  2143. }
  2144. } else if (CurMethod->isInstanceMethod()) {
  2145. // We should warn if a local variable hides an ivar.
  2146. if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
  2147. ObjCInterfaceDecl *ClassDeclared;
  2148. if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
  2149. if (IV->getAccessControl() != ObjCIvarDecl::Private ||
  2150. declaresSameEntity(IFace, ClassDeclared))
  2151. Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
  2152. }
  2153. }
  2154. } else if (Lookup.isSingleResult() &&
  2155. Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
  2156. // If accessing a stand-alone ivar in a class method, this is an error.
  2157. if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
  2158. return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
  2159. << IV->getDeclName());
  2160. }
  2161. if (Lookup.empty() && II && AllowBuiltinCreation) {
  2162. // FIXME. Consolidate this with similar code in LookupName.
  2163. if (unsigned BuiltinID = II->getBuiltinID()) {
  2164. if (!(getLangOpts().CPlusPlus &&
  2165. Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
  2166. NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
  2167. S, Lookup.isForRedeclaration(),
  2168. Lookup.getNameLoc());
  2169. if (D) Lookup.addDecl(D);
  2170. }
  2171. }
  2172. }
  2173. // Sentinel value saying that we didn't do anything special.
  2174. return ExprResult((Expr *)nullptr);
  2175. }
  2176. /// \brief Cast a base object to a member's actual type.
  2177. ///
  2178. /// Logically this happens in three phases:
  2179. ///
  2180. /// * First we cast from the base type to the naming class.
  2181. /// The naming class is the class into which we were looking
  2182. /// when we found the member; it's the qualifier type if a
  2183. /// qualifier was provided, and otherwise it's the base type.
  2184. ///
  2185. /// * Next we cast from the naming class to the declaring class.
  2186. /// If the member we found was brought into a class's scope by
  2187. /// a using declaration, this is that class; otherwise it's
  2188. /// the class declaring the member.
  2189. ///
  2190. /// * Finally we cast from the declaring class to the "true"
  2191. /// declaring class of the member. This conversion does not
  2192. /// obey access control.
  2193. ExprResult
  2194. Sema::PerformObjectMemberConversion(Expr *From,
  2195. NestedNameSpecifier *Qualifier,
  2196. NamedDecl *FoundDecl,
  2197. NamedDecl *Member) {
  2198. CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
  2199. if (!RD)
  2200. return From;
  2201. QualType DestRecordType;
  2202. QualType DestType;
  2203. QualType FromRecordType;
  2204. QualType FromType = From->getType();
  2205. bool PointerConversions = false;
  2206. if (isa<FieldDecl>(Member)) {
  2207. DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
  2208. if (FromType->getAs<PointerType>()) {
  2209. DestType = Context.getPointerType(DestRecordType);
  2210. FromRecordType = FromType->getPointeeType();
  2211. PointerConversions = true;
  2212. } else {
  2213. DestType = DestRecordType;
  2214. FromRecordType = FromType;
  2215. }
  2216. } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
  2217. if (Method->isStatic())
  2218. return From;
  2219. DestType = Method->getThisType(Context);
  2220. DestRecordType = DestType->getPointeeType();
  2221. if (FromType->getAs<PointerType>()) {
  2222. FromRecordType = FromType->getPointeeType();
  2223. PointerConversions = true;
  2224. } else {
  2225. FromRecordType = FromType;
  2226. DestType = DestRecordType;
  2227. }
  2228. } else {
  2229. // No conversion necessary.
  2230. return From;
  2231. }
  2232. if (DestType->isDependentType() || FromType->isDependentType())
  2233. return From;
  2234. // If the unqualified types are the same, no conversion is necessary.
  2235. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2236. return From;
  2237. SourceRange FromRange = From->getSourceRange();
  2238. SourceLocation FromLoc = FromRange.getBegin();
  2239. ExprValueKind VK = From->getValueKind();
  2240. // C++ [class.member.lookup]p8:
  2241. // [...] Ambiguities can often be resolved by qualifying a name with its
  2242. // class name.
  2243. //
  2244. // If the member was a qualified name and the qualified referred to a
  2245. // specific base subobject type, we'll cast to that intermediate type
  2246. // first and then to the object in which the member is declared. That allows
  2247. // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
  2248. //
  2249. // class Base { public: int x; };
  2250. // class Derived1 : public Base { };
  2251. // class Derived2 : public Base { };
  2252. // class VeryDerived : public Derived1, public Derived2 { void f(); };
  2253. //
  2254. // void VeryDerived::f() {
  2255. // x = 17; // error: ambiguous base subobjects
  2256. // Derived1::x = 17; // okay, pick the Base subobject of Derived1
  2257. // }
  2258. if (Qualifier && Qualifier->getAsType()) {
  2259. QualType QType = QualType(Qualifier->getAsType(), 0);
  2260. assert(QType->isRecordType() && "lookup done with non-record type");
  2261. QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
  2262. // In C++98, the qualifier type doesn't actually have to be a base
  2263. // type of the object type, in which case we just ignore it.
  2264. // Otherwise build the appropriate casts.
  2265. if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
  2266. CXXCastPath BasePath;
  2267. if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
  2268. FromLoc, FromRange, &BasePath))
  2269. return ExprError();
  2270. if (PointerConversions)
  2271. QType = Context.getPointerType(QType);
  2272. From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
  2273. VK, &BasePath).get();
  2274. FromType = QType;
  2275. FromRecordType = QRecordType;
  2276. // If the qualifier type was the same as the destination type,
  2277. // we're done.
  2278. if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
  2279. return From;
  2280. }
  2281. }
  2282. bool IgnoreAccess = false;
  2283. // If we actually found the member through a using declaration, cast
  2284. // down to the using declaration's type.
  2285. //
  2286. // Pointer equality is fine here because only one declaration of a
  2287. // class ever has member declarations.
  2288. if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
  2289. assert(isa<UsingShadowDecl>(FoundDecl));
  2290. QualType URecordType = Context.getTypeDeclType(
  2291. cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
  2292. // We only need to do this if the naming-class to declaring-class
  2293. // conversion is non-trivial.
  2294. if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
  2295. assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
  2296. CXXCastPath BasePath;
  2297. if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
  2298. FromLoc, FromRange, &BasePath))
  2299. return ExprError();
  2300. QualType UType = URecordType;
  2301. if (PointerConversions)
  2302. UType = Context.getPointerType(UType);
  2303. From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
  2304. VK, &BasePath).get();
  2305. FromType = UType;
  2306. FromRecordType = URecordType;
  2307. }
  2308. // We don't do access control for the conversion from the
  2309. // declaring class to the true declaring class.
  2310. IgnoreAccess = true;
  2311. }
  2312. CXXCastPath BasePath;
  2313. if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
  2314. FromLoc, FromRange, &BasePath,
  2315. IgnoreAccess))
  2316. return ExprError();
  2317. return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
  2318. VK, &BasePath);
  2319. }
  2320. bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
  2321. const LookupResult &R,
  2322. bool HasTrailingLParen) {
  2323. // Only when used directly as the postfix-expression of a call.
  2324. if (!HasTrailingLParen)
  2325. return false;
  2326. // Never if a scope specifier was provided.
  2327. if (SS.isSet())
  2328. return false;
  2329. // Only in C++ or ObjC++.
  2330. if (!getLangOpts().CPlusPlus)
  2331. return false;
  2332. // Turn off ADL when we find certain kinds of declarations during
  2333. // normal lookup:
  2334. for (NamedDecl *D : R) {
  2335. // C++0x [basic.lookup.argdep]p3:
  2336. // -- a declaration of a class member
  2337. // Since using decls preserve this property, we check this on the
  2338. // original decl.
  2339. if (D->isCXXClassMember())
  2340. return false;
  2341. // C++0x [basic.lookup.argdep]p3:
  2342. // -- a block-scope function declaration that is not a
  2343. // using-declaration
  2344. // NOTE: we also trigger this for function templates (in fact, we
  2345. // don't check the decl type at all, since all other decl types
  2346. // turn off ADL anyway).
  2347. if (isa<UsingShadowDecl>(D))
  2348. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2349. else if (D->getLexicalDeclContext()->isFunctionOrMethod())
  2350. return false;
  2351. // C++0x [basic.lookup.argdep]p3:
  2352. // -- a declaration that is neither a function or a function
  2353. // template
  2354. // And also for builtin functions.
  2355. if (isa<FunctionDecl>(D)) {
  2356. FunctionDecl *FDecl = cast<FunctionDecl>(D);
  2357. // But also builtin functions.
  2358. if (FDecl->getBuiltinID() && FDecl->isImplicit())
  2359. return false;
  2360. } else if (!isa<FunctionTemplateDecl>(D))
  2361. return false;
  2362. }
  2363. return true;
  2364. }
  2365. /// Diagnoses obvious problems with the use of the given declaration
  2366. /// as an expression. This is only actually called for lookups that
  2367. /// were not overloaded, and it doesn't promise that the declaration
  2368. /// will in fact be used.
  2369. static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
  2370. if (D->isInvalidDecl())
  2371. return true;
  2372. if (isa<TypedefNameDecl>(D)) {
  2373. S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
  2374. return true;
  2375. }
  2376. if (isa<ObjCInterfaceDecl>(D)) {
  2377. S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
  2378. return true;
  2379. }
  2380. if (isa<NamespaceDecl>(D)) {
  2381. S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
  2382. return true;
  2383. }
  2384. return false;
  2385. }
  2386. ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
  2387. LookupResult &R, bool NeedsADL,
  2388. bool AcceptInvalidDecl) {
  2389. // If this is a single, fully-resolved result and we don't need ADL,
  2390. // just build an ordinary singleton decl ref.
  2391. if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
  2392. return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
  2393. R.getRepresentativeDecl(), nullptr,
  2394. AcceptInvalidDecl);
  2395. // We only need to check the declaration if there's exactly one
  2396. // result, because in the overloaded case the results can only be
  2397. // functions and function templates.
  2398. if (R.isSingleResult() &&
  2399. CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
  2400. return ExprError();
  2401. // Otherwise, just build an unresolved lookup expression. Suppress
  2402. // any lookup-related diagnostics; we'll hash these out later, when
  2403. // we've picked a target.
  2404. R.suppressDiagnostics();
  2405. UnresolvedLookupExpr *ULE
  2406. = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
  2407. SS.getWithLocInContext(Context),
  2408. R.getLookupNameInfo(),
  2409. NeedsADL, R.isOverloadedResult(),
  2410. R.begin(), R.end());
  2411. return ULE;
  2412. }
  2413. static void
  2414. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  2415. ValueDecl *var, DeclContext *DC);
  2416. /// \brief Complete semantic analysis for a reference to the given declaration.
  2417. ExprResult Sema::BuildDeclarationNameExpr(
  2418. const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
  2419. NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
  2420. bool AcceptInvalidDecl) {
  2421. assert(D && "Cannot refer to a NULL declaration");
  2422. assert(!isa<FunctionTemplateDecl>(D) &&
  2423. "Cannot refer unambiguously to a function template");
  2424. SourceLocation Loc = NameInfo.getLoc();
  2425. if (CheckDeclInExpr(*this, Loc, D))
  2426. return ExprError();
  2427. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
  2428. // Specifically diagnose references to class templates that are missing
  2429. // a template argument list.
  2430. Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
  2431. << Template << SS.getRange();
  2432. Diag(Template->getLocation(), diag::note_template_decl_here);
  2433. return ExprError();
  2434. }
  2435. // Make sure that we're referring to a value.
  2436. ValueDecl *VD = dyn_cast<ValueDecl>(D);
  2437. if (!VD) {
  2438. Diag(Loc, diag::err_ref_non_value)
  2439. << D << SS.getRange();
  2440. Diag(D->getLocation(), diag::note_declared_at);
  2441. return ExprError();
  2442. }
  2443. // Check whether this declaration can be used. Note that we suppress
  2444. // this check when we're going to perform argument-dependent lookup
  2445. // on this function name, because this might not be the function
  2446. // that overload resolution actually selects.
  2447. if (DiagnoseUseOfDecl(VD, Loc))
  2448. return ExprError();
  2449. // Only create DeclRefExpr's for valid Decl's.
  2450. if (VD->isInvalidDecl() && !AcceptInvalidDecl)
  2451. return ExprError();
  2452. // Handle members of anonymous structs and unions. If we got here,
  2453. // and the reference is to a class member indirect field, then this
  2454. // must be the subject of a pointer-to-member expression.
  2455. if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
  2456. if (!indirectField->isCXXClassMember())
  2457. return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
  2458. indirectField);
  2459. {
  2460. QualType type = VD->getType();
  2461. if (type.isNull())
  2462. return ExprError();
  2463. if (auto *FPT = type->getAs<FunctionProtoType>()) {
  2464. // C++ [except.spec]p17:
  2465. // An exception-specification is considered to be needed when:
  2466. // - in an expression, the function is the unique lookup result or
  2467. // the selected member of a set of overloaded functions.
  2468. ResolveExceptionSpec(Loc, FPT);
  2469. type = VD->getType();
  2470. }
  2471. ExprValueKind valueKind = VK_RValue;
  2472. switch (D->getKind()) {
  2473. // Ignore all the non-ValueDecl kinds.
  2474. #define ABSTRACT_DECL(kind)
  2475. #define VALUE(type, base)
  2476. #define DECL(type, base) \
  2477. case Decl::type:
  2478. #include "clang/AST/DeclNodes.inc"
  2479. llvm_unreachable("invalid value decl kind");
  2480. // These shouldn't make it here.
  2481. case Decl::ObjCAtDefsField:
  2482. case Decl::ObjCIvar:
  2483. llvm_unreachable("forming non-member reference to ivar?");
  2484. // Enum constants are always r-values and never references.
  2485. // Unresolved using declarations are dependent.
  2486. case Decl::EnumConstant:
  2487. case Decl::UnresolvedUsingValue:
  2488. case Decl::OMPDeclareReduction:
  2489. valueKind = VK_RValue;
  2490. break;
  2491. // Fields and indirect fields that got here must be for
  2492. // pointer-to-member expressions; we just call them l-values for
  2493. // internal consistency, because this subexpression doesn't really
  2494. // exist in the high-level semantics.
  2495. case Decl::Field:
  2496. case Decl::IndirectField:
  2497. assert(getLangOpts().CPlusPlus &&
  2498. "building reference to field in C?");
  2499. // These can't have reference type in well-formed programs, but
  2500. // for internal consistency we do this anyway.
  2501. type = type.getNonReferenceType();
  2502. valueKind = VK_LValue;
  2503. break;
  2504. // Non-type template parameters are either l-values or r-values
  2505. // depending on the type.
  2506. case Decl::NonTypeTemplateParm: {
  2507. if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
  2508. type = reftype->getPointeeType();
  2509. valueKind = VK_LValue; // even if the parameter is an r-value reference
  2510. break;
  2511. }
  2512. // For non-references, we need to strip qualifiers just in case
  2513. // the template parameter was declared as 'const int' or whatever.
  2514. valueKind = VK_RValue;
  2515. type = type.getUnqualifiedType();
  2516. break;
  2517. }
  2518. case Decl::Var:
  2519. case Decl::VarTemplateSpecialization:
  2520. case Decl::VarTemplatePartialSpecialization:
  2521. case Decl::Decomposition:
  2522. case Decl::OMPCapturedExpr:
  2523. // In C, "extern void blah;" is valid and is an r-value.
  2524. if (!getLangOpts().CPlusPlus &&
  2525. !type.hasQualifiers() &&
  2526. type->isVoidType()) {
  2527. valueKind = VK_RValue;
  2528. break;
  2529. }
  2530. // fallthrough
  2531. case Decl::ImplicitParam:
  2532. case Decl::ParmVar: {
  2533. // These are always l-values.
  2534. valueKind = VK_LValue;
  2535. type = type.getNonReferenceType();
  2536. // FIXME: Does the addition of const really only apply in
  2537. // potentially-evaluated contexts? Since the variable isn't actually
  2538. // captured in an unevaluated context, it seems that the answer is no.
  2539. if (!isUnevaluatedContext()) {
  2540. QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
  2541. if (!CapturedType.isNull())
  2542. type = CapturedType;
  2543. }
  2544. break;
  2545. }
  2546. case Decl::Binding: {
  2547. // These are always lvalues.
  2548. valueKind = VK_LValue;
  2549. type = type.getNonReferenceType();
  2550. // FIXME: Support lambda-capture of BindingDecls, once CWG actually
  2551. // decides how that's supposed to work.
  2552. auto *BD = cast<BindingDecl>(VD);
  2553. if (BD->getDeclContext()->isFunctionOrMethod() &&
  2554. BD->getDeclContext() != CurContext)
  2555. diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
  2556. break;
  2557. }
  2558. case Decl::Function: {
  2559. if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
  2560. if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
  2561. type = Context.BuiltinFnTy;
  2562. valueKind = VK_RValue;
  2563. break;
  2564. }
  2565. }
  2566. const FunctionType *fty = type->castAs<FunctionType>();
  2567. // If we're referring to a function with an __unknown_anytype
  2568. // result type, make the entire expression __unknown_anytype.
  2569. if (fty->getReturnType() == Context.UnknownAnyTy) {
  2570. type = Context.UnknownAnyTy;
  2571. valueKind = VK_RValue;
  2572. break;
  2573. }
  2574. // Functions are l-values in C++.
  2575. if (getLangOpts().CPlusPlus) {
  2576. valueKind = VK_LValue;
  2577. break;
  2578. }
  2579. // C99 DR 316 says that, if a function type comes from a
  2580. // function definition (without a prototype), that type is only
  2581. // used for checking compatibility. Therefore, when referencing
  2582. // the function, we pretend that we don't have the full function
  2583. // type.
  2584. if (!cast<FunctionDecl>(VD)->hasPrototype() &&
  2585. isa<FunctionProtoType>(fty))
  2586. type = Context.getFunctionNoProtoType(fty->getReturnType(),
  2587. fty->getExtInfo());
  2588. // Functions are r-values in C.
  2589. valueKind = VK_RValue;
  2590. break;
  2591. }
  2592. case Decl::CXXDeductionGuide:
  2593. llvm_unreachable("building reference to deduction guide");
  2594. case Decl::MSProperty:
  2595. valueKind = VK_LValue;
  2596. break;
  2597. case Decl::CXXMethod:
  2598. // If we're referring to a method with an __unknown_anytype
  2599. // result type, make the entire expression __unknown_anytype.
  2600. // This should only be possible with a type written directly.
  2601. if (const FunctionProtoType *proto
  2602. = dyn_cast<FunctionProtoType>(VD->getType()))
  2603. if (proto->getReturnType() == Context.UnknownAnyTy) {
  2604. type = Context.UnknownAnyTy;
  2605. valueKind = VK_RValue;
  2606. break;
  2607. }
  2608. // C++ methods are l-values if static, r-values if non-static.
  2609. if (cast<CXXMethodDecl>(VD)->isStatic()) {
  2610. valueKind = VK_LValue;
  2611. break;
  2612. }
  2613. // fallthrough
  2614. case Decl::CXXConversion:
  2615. case Decl::CXXDestructor:
  2616. case Decl::CXXConstructor:
  2617. valueKind = VK_RValue;
  2618. break;
  2619. }
  2620. return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
  2621. TemplateArgs);
  2622. }
  2623. }
  2624. static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
  2625. SmallString<32> &Target) {
  2626. Target.resize(CharByteWidth * (Source.size() + 1));
  2627. char *ResultPtr = &Target[0];
  2628. const llvm::UTF8 *ErrorPtr;
  2629. bool success =
  2630. llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
  2631. (void)success;
  2632. assert(success);
  2633. Target.resize(ResultPtr - &Target[0]);
  2634. }
  2635. ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
  2636. PredefinedExpr::IdentType IT) {
  2637. // Pick the current block, lambda, captured statement or function.
  2638. Decl *currentDecl = nullptr;
  2639. if (const BlockScopeInfo *BSI = getCurBlock())
  2640. currentDecl = BSI->TheDecl;
  2641. else if (const LambdaScopeInfo *LSI = getCurLambda())
  2642. currentDecl = LSI->CallOperator;
  2643. else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
  2644. currentDecl = CSI->TheCapturedDecl;
  2645. else
  2646. currentDecl = getCurFunctionOrMethodDecl();
  2647. if (!currentDecl) {
  2648. Diag(Loc, diag::ext_predef_outside_function);
  2649. currentDecl = Context.getTranslationUnitDecl();
  2650. }
  2651. QualType ResTy;
  2652. StringLiteral *SL = nullptr;
  2653. if (cast<DeclContext>(currentDecl)->isDependentContext())
  2654. ResTy = Context.DependentTy;
  2655. else {
  2656. // Pre-defined identifiers are of type char[x], where x is the length of
  2657. // the string.
  2658. auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
  2659. unsigned Length = Str.length();
  2660. llvm::APInt LengthI(32, Length + 1);
  2661. if (IT == PredefinedExpr::LFunction) {
  2662. ResTy = Context.WideCharTy.withConst();
  2663. SmallString<32> RawChars;
  2664. ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
  2665. Str, RawChars);
  2666. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2667. /*IndexTypeQuals*/ 0);
  2668. SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
  2669. /*Pascal*/ false, ResTy, Loc);
  2670. } else {
  2671. ResTy = Context.CharTy.withConst();
  2672. ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
  2673. /*IndexTypeQuals*/ 0);
  2674. SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
  2675. /*Pascal*/ false, ResTy, Loc);
  2676. }
  2677. }
  2678. return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
  2679. }
  2680. ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
  2681. PredefinedExpr::IdentType IT;
  2682. switch (Kind) {
  2683. default: llvm_unreachable("Unknown simple primary expr!");
  2684. case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
  2685. case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
  2686. case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
  2687. case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
  2688. case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
  2689. case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
  2690. }
  2691. return BuildPredefinedExpr(Loc, IT);
  2692. }
  2693. ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
  2694. SmallString<16> CharBuffer;
  2695. bool Invalid = false;
  2696. StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
  2697. if (Invalid)
  2698. return ExprError();
  2699. CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
  2700. PP, Tok.getKind());
  2701. if (Literal.hadError())
  2702. return ExprError();
  2703. QualType Ty;
  2704. if (Literal.isWide())
  2705. Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
  2706. else if (Literal.isUTF16())
  2707. Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
  2708. else if (Literal.isUTF32())
  2709. Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
  2710. else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
  2711. Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
  2712. else
  2713. Ty = Context.CharTy; // 'x' -> char in C++
  2714. CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
  2715. if (Literal.isWide())
  2716. Kind = CharacterLiteral::Wide;
  2717. else if (Literal.isUTF16())
  2718. Kind = CharacterLiteral::UTF16;
  2719. else if (Literal.isUTF32())
  2720. Kind = CharacterLiteral::UTF32;
  2721. else if (Literal.isUTF8())
  2722. Kind = CharacterLiteral::UTF8;
  2723. Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
  2724. Tok.getLocation());
  2725. if (Literal.getUDSuffix().empty())
  2726. return Lit;
  2727. // We're building a user-defined literal.
  2728. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2729. SourceLocation UDSuffixLoc =
  2730. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2731. // Make sure we're allowed user-defined literals here.
  2732. if (!UDLScope)
  2733. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
  2734. // C++11 [lex.ext]p6: The literal L is treated as a call of the form
  2735. // operator "" X (ch)
  2736. return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
  2737. Lit, Tok.getLocation());
  2738. }
  2739. ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
  2740. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2741. return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
  2742. Context.IntTy, Loc);
  2743. }
  2744. static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
  2745. QualType Ty, SourceLocation Loc) {
  2746. const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
  2747. using llvm::APFloat;
  2748. APFloat Val(Format);
  2749. APFloat::opStatus result = Literal.GetFloatValue(Val);
  2750. // Overflow is always an error, but underflow is only an error if
  2751. // we underflowed to zero (APFloat reports denormals as underflow).
  2752. if ((result & APFloat::opOverflow) ||
  2753. ((result & APFloat::opUnderflow) && Val.isZero())) {
  2754. unsigned diagnostic;
  2755. SmallString<20> buffer;
  2756. if (result & APFloat::opOverflow) {
  2757. diagnostic = diag::warn_float_overflow;
  2758. APFloat::getLargest(Format).toString(buffer);
  2759. } else {
  2760. diagnostic = diag::warn_float_underflow;
  2761. APFloat::getSmallest(Format).toString(buffer);
  2762. }
  2763. S.Diag(Loc, diagnostic)
  2764. << Ty
  2765. << StringRef(buffer.data(), buffer.size());
  2766. }
  2767. bool isExact = (result == APFloat::opOK);
  2768. return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
  2769. }
  2770. bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
  2771. assert(E && "Invalid expression");
  2772. if (E->isValueDependent())
  2773. return false;
  2774. QualType QT = E->getType();
  2775. if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
  2776. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
  2777. return true;
  2778. }
  2779. llvm::APSInt ValueAPS;
  2780. ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
  2781. if (R.isInvalid())
  2782. return true;
  2783. bool ValueIsPositive = ValueAPS.isStrictlyPositive();
  2784. if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
  2785. Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
  2786. << ValueAPS.toString(10) << ValueIsPositive;
  2787. return true;
  2788. }
  2789. return false;
  2790. }
  2791. ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
  2792. // Fast path for a single digit (which is quite common). A single digit
  2793. // cannot have a trigraph, escaped newline, radix prefix, or suffix.
  2794. if (Tok.getLength() == 1) {
  2795. const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
  2796. return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
  2797. }
  2798. SmallString<128> SpellingBuffer;
  2799. // NumericLiteralParser wants to overread by one character. Add padding to
  2800. // the buffer in case the token is copied to the buffer. If getSpelling()
  2801. // returns a StringRef to the memory buffer, it should have a null char at
  2802. // the EOF, so it is also safe.
  2803. SpellingBuffer.resize(Tok.getLength() + 1);
  2804. // Get the spelling of the token, which eliminates trigraphs, etc.
  2805. bool Invalid = false;
  2806. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  2807. if (Invalid)
  2808. return ExprError();
  2809. NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
  2810. if (Literal.hadError)
  2811. return ExprError();
  2812. if (Literal.hasUDSuffix()) {
  2813. // We're building a user-defined literal.
  2814. IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
  2815. SourceLocation UDSuffixLoc =
  2816. getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
  2817. // Make sure we're allowed user-defined literals here.
  2818. if (!UDLScope)
  2819. return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
  2820. QualType CookedTy;
  2821. if (Literal.isFloatingLiteral()) {
  2822. // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
  2823. // long double, the literal is treated as a call of the form
  2824. // operator "" X (f L)
  2825. CookedTy = Context.LongDoubleTy;
  2826. } else {
  2827. // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
  2828. // unsigned long long, the literal is treated as a call of the form
  2829. // operator "" X (n ULL)
  2830. CookedTy = Context.UnsignedLongLongTy;
  2831. }
  2832. DeclarationName OpName =
  2833. Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
  2834. DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
  2835. OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
  2836. SourceLocation TokLoc = Tok.getLocation();
  2837. // Perform literal operator lookup to determine if we're building a raw
  2838. // literal or a cooked one.
  2839. LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
  2840. switch (LookupLiteralOperator(UDLScope, R, CookedTy,
  2841. /*AllowRaw*/ true, /*AllowTemplate*/ true,
  2842. /*AllowStringTemplate*/ false,
  2843. /*DiagnoseMissing*/ !Literal.isImaginary)) {
  2844. case LOLR_ErrorNoDiagnostic:
  2845. // Lookup failure for imaginary constants isn't fatal, there's still the
  2846. // GNU extension producing _Complex types.
  2847. break;
  2848. case LOLR_Error:
  2849. return ExprError();
  2850. case LOLR_Cooked: {
  2851. Expr *Lit;
  2852. if (Literal.isFloatingLiteral()) {
  2853. Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
  2854. } else {
  2855. llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
  2856. if (Literal.GetIntegerValue(ResultVal))
  2857. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2858. << /* Unsigned */ 1;
  2859. Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
  2860. Tok.getLocation());
  2861. }
  2862. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2863. }
  2864. case LOLR_Raw: {
  2865. // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
  2866. // literal is treated as a call of the form
  2867. // operator "" X ("n")
  2868. unsigned Length = Literal.getUDSuffixOffset();
  2869. QualType StrTy = Context.getConstantArrayType(
  2870. Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
  2871. ArrayType::Normal, 0);
  2872. Expr *Lit = StringLiteral::Create(
  2873. Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
  2874. /*Pascal*/false, StrTy, &TokLoc, 1);
  2875. return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
  2876. }
  2877. case LOLR_Template: {
  2878. // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
  2879. // template), L is treated as a call fo the form
  2880. // operator "" X <'c1', 'c2', ... 'ck'>()
  2881. // where n is the source character sequence c1 c2 ... ck.
  2882. TemplateArgumentListInfo ExplicitArgs;
  2883. unsigned CharBits = Context.getIntWidth(Context.CharTy);
  2884. bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
  2885. llvm::APSInt Value(CharBits, CharIsUnsigned);
  2886. for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
  2887. Value = TokSpelling[I];
  2888. TemplateArgument Arg(Context, Value, Context.CharTy);
  2889. TemplateArgumentLocInfo ArgInfo;
  2890. ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
  2891. }
  2892. return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
  2893. &ExplicitArgs);
  2894. }
  2895. case LOLR_StringTemplate:
  2896. llvm_unreachable("unexpected literal operator lookup result");
  2897. }
  2898. }
  2899. Expr *Res;
  2900. if (Literal.isFloatingLiteral()) {
  2901. QualType Ty;
  2902. if (Literal.isHalf){
  2903. if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
  2904. Ty = Context.HalfTy;
  2905. else {
  2906. Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
  2907. return ExprError();
  2908. }
  2909. } else if (Literal.isFloat)
  2910. Ty = Context.FloatTy;
  2911. else if (Literal.isLong)
  2912. Ty = Context.LongDoubleTy;
  2913. else if (Literal.isFloat16)
  2914. Ty = Context.Float16Ty;
  2915. else if (Literal.isFloat128)
  2916. Ty = Context.Float128Ty;
  2917. else
  2918. Ty = Context.DoubleTy;
  2919. Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
  2920. if (Ty == Context.DoubleTy) {
  2921. if (getLangOpts().SinglePrecisionConstants) {
  2922. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  2923. if (BTy->getKind() != BuiltinType::Float) {
  2924. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2925. }
  2926. } else if (getLangOpts().OpenCL &&
  2927. !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
  2928. // Impose single-precision float type when cl_khr_fp64 is not enabled.
  2929. Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
  2930. Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
  2931. }
  2932. }
  2933. } else if (!Literal.isIntegerLiteral()) {
  2934. return ExprError();
  2935. } else {
  2936. QualType Ty;
  2937. // 'long long' is a C99 or C++11 feature.
  2938. if (!getLangOpts().C99 && Literal.isLongLong) {
  2939. if (getLangOpts().CPlusPlus)
  2940. Diag(Tok.getLocation(),
  2941. getLangOpts().CPlusPlus11 ?
  2942. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  2943. else
  2944. Diag(Tok.getLocation(), diag::ext_c99_longlong);
  2945. }
  2946. // Get the value in the widest-possible width.
  2947. unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
  2948. llvm::APInt ResultVal(MaxWidth, 0);
  2949. if (Literal.GetIntegerValue(ResultVal)) {
  2950. // If this value didn't fit into uintmax_t, error and force to ull.
  2951. Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
  2952. << /* Unsigned */ 1;
  2953. Ty = Context.UnsignedLongLongTy;
  2954. assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
  2955. "long long is not intmax_t?");
  2956. } else {
  2957. // If this value fits into a ULL, try to figure out what else it fits into
  2958. // according to the rules of C99 6.4.4.1p5.
  2959. // Octal, Hexadecimal, and integers with a U suffix are allowed to
  2960. // be an unsigned int.
  2961. bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
  2962. // Check from smallest to largest, picking the smallest type we can.
  2963. unsigned Width = 0;
  2964. // Microsoft specific integer suffixes are explicitly sized.
  2965. if (Literal.MicrosoftInteger) {
  2966. if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
  2967. Width = 8;
  2968. Ty = Context.CharTy;
  2969. } else {
  2970. Width = Literal.MicrosoftInteger;
  2971. Ty = Context.getIntTypeForBitwidth(Width,
  2972. /*Signed=*/!Literal.isUnsigned);
  2973. }
  2974. }
  2975. if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
  2976. // Are int/unsigned possibilities?
  2977. unsigned IntSize = Context.getTargetInfo().getIntWidth();
  2978. // Does it fit in a unsigned int?
  2979. if (ResultVal.isIntN(IntSize)) {
  2980. // Does it fit in a signed int?
  2981. if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
  2982. Ty = Context.IntTy;
  2983. else if (AllowUnsigned)
  2984. Ty = Context.UnsignedIntTy;
  2985. Width = IntSize;
  2986. }
  2987. }
  2988. // Are long/unsigned long possibilities?
  2989. if (Ty.isNull() && !Literal.isLongLong) {
  2990. unsigned LongSize = Context.getTargetInfo().getLongWidth();
  2991. // Does it fit in a unsigned long?
  2992. if (ResultVal.isIntN(LongSize)) {
  2993. // Does it fit in a signed long?
  2994. if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
  2995. Ty = Context.LongTy;
  2996. else if (AllowUnsigned)
  2997. Ty = Context.UnsignedLongTy;
  2998. // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
  2999. // is compatible.
  3000. else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
  3001. const unsigned LongLongSize =
  3002. Context.getTargetInfo().getLongLongWidth();
  3003. Diag(Tok.getLocation(),
  3004. getLangOpts().CPlusPlus
  3005. ? Literal.isLong
  3006. ? diag::warn_old_implicitly_unsigned_long_cxx
  3007. : /*C++98 UB*/ diag::
  3008. ext_old_implicitly_unsigned_long_cxx
  3009. : diag::warn_old_implicitly_unsigned_long)
  3010. << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
  3011. : /*will be ill-formed*/ 1);
  3012. Ty = Context.UnsignedLongTy;
  3013. }
  3014. Width = LongSize;
  3015. }
  3016. }
  3017. // Check long long if needed.
  3018. if (Ty.isNull()) {
  3019. unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
  3020. // Does it fit in a unsigned long long?
  3021. if (ResultVal.isIntN(LongLongSize)) {
  3022. // Does it fit in a signed long long?
  3023. // To be compatible with MSVC, hex integer literals ending with the
  3024. // LL or i64 suffix are always signed in Microsoft mode.
  3025. if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
  3026. (getLangOpts().MSVCCompat && Literal.isLongLong)))
  3027. Ty = Context.LongLongTy;
  3028. else if (AllowUnsigned)
  3029. Ty = Context.UnsignedLongLongTy;
  3030. Width = LongLongSize;
  3031. }
  3032. }
  3033. // If we still couldn't decide a type, we probably have something that
  3034. // does not fit in a signed long long, but has no U suffix.
  3035. if (Ty.isNull()) {
  3036. Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
  3037. Ty = Context.UnsignedLongLongTy;
  3038. Width = Context.getTargetInfo().getLongLongWidth();
  3039. }
  3040. if (ResultVal.getBitWidth() != Width)
  3041. ResultVal = ResultVal.trunc(Width);
  3042. }
  3043. Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
  3044. }
  3045. // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
  3046. if (Literal.isImaginary) {
  3047. Res = new (Context) ImaginaryLiteral(Res,
  3048. Context.getComplexType(Res->getType()));
  3049. Diag(Tok.getLocation(), diag::ext_imaginary_constant);
  3050. }
  3051. return Res;
  3052. }
  3053. ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
  3054. assert(E && "ActOnParenExpr() missing expr");
  3055. return new (Context) ParenExpr(L, R, E);
  3056. }
  3057. static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
  3058. SourceLocation Loc,
  3059. SourceRange ArgRange) {
  3060. // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
  3061. // scalar or vector data type argument..."
  3062. // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
  3063. // type (C99 6.2.5p18) or void.
  3064. if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
  3065. S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
  3066. << T << ArgRange;
  3067. return true;
  3068. }
  3069. assert((T->isVoidType() || !T->isIncompleteType()) &&
  3070. "Scalar types should always be complete");
  3071. return false;
  3072. }
  3073. static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
  3074. SourceLocation Loc,
  3075. SourceRange ArgRange,
  3076. UnaryExprOrTypeTrait TraitKind) {
  3077. // Invalid types must be hard errors for SFINAE in C++.
  3078. if (S.LangOpts.CPlusPlus)
  3079. return true;
  3080. // C99 6.5.3.4p1:
  3081. if (T->isFunctionType() &&
  3082. (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
  3083. // sizeof(function)/alignof(function) is allowed as an extension.
  3084. S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
  3085. << TraitKind << ArgRange;
  3086. return false;
  3087. }
  3088. // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
  3089. // this is an error (OpenCL v1.1 s6.3.k)
  3090. if (T->isVoidType()) {
  3091. unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
  3092. : diag::ext_sizeof_alignof_void_type;
  3093. S.Diag(Loc, DiagID) << TraitKind << ArgRange;
  3094. return false;
  3095. }
  3096. return true;
  3097. }
  3098. static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
  3099. SourceLocation Loc,
  3100. SourceRange ArgRange,
  3101. UnaryExprOrTypeTrait TraitKind) {
  3102. // Reject sizeof(interface) and sizeof(interface<proto>) if the
  3103. // runtime doesn't allow it.
  3104. if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
  3105. S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
  3106. << T << (TraitKind == UETT_SizeOf)
  3107. << ArgRange;
  3108. return true;
  3109. }
  3110. return false;
  3111. }
  3112. /// \brief Check whether E is a pointer from a decayed array type (the decayed
  3113. /// pointer type is equal to T) and emit a warning if it is.
  3114. static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
  3115. Expr *E) {
  3116. // Don't warn if the operation changed the type.
  3117. if (T != E->getType())
  3118. return;
  3119. // Now look for array decays.
  3120. ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
  3121. if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
  3122. return;
  3123. S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
  3124. << ICE->getType()
  3125. << ICE->getSubExpr()->getType();
  3126. }
  3127. /// \brief Check the constraints on expression operands to unary type expression
  3128. /// and type traits.
  3129. ///
  3130. /// Completes any types necessary and validates the constraints on the operand
  3131. /// expression. The logic mostly mirrors the type-based overload, but may modify
  3132. /// the expression as it completes the type for that expression through template
  3133. /// instantiation, etc.
  3134. bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
  3135. UnaryExprOrTypeTrait ExprKind) {
  3136. QualType ExprTy = E->getType();
  3137. assert(!ExprTy->isReferenceType());
  3138. if (ExprKind == UETT_VecStep)
  3139. return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3140. E->getSourceRange());
  3141. // Whitelist some types as extensions
  3142. if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
  3143. E->getSourceRange(), ExprKind))
  3144. return false;
  3145. // 'alignof' applied to an expression only requires the base element type of
  3146. // the expression to be complete. 'sizeof' requires the expression's type to
  3147. // be complete (and will attempt to complete it if it's an array of unknown
  3148. // bound).
  3149. if (ExprKind == UETT_AlignOf) {
  3150. if (RequireCompleteType(E->getExprLoc(),
  3151. Context.getBaseElementType(E->getType()),
  3152. diag::err_sizeof_alignof_incomplete_type, ExprKind,
  3153. E->getSourceRange()))
  3154. return true;
  3155. } else {
  3156. if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
  3157. ExprKind, E->getSourceRange()))
  3158. return true;
  3159. }
  3160. // Completing the expression's type may have changed it.
  3161. ExprTy = E->getType();
  3162. assert(!ExprTy->isReferenceType());
  3163. if (ExprTy->isFunctionType()) {
  3164. Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
  3165. << ExprKind << E->getSourceRange();
  3166. return true;
  3167. }
  3168. // The operand for sizeof and alignof is in an unevaluated expression context,
  3169. // so side effects could result in unintended consequences.
  3170. if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
  3171. !inTemplateInstantiation() && E->HasSideEffects(Context, false))
  3172. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  3173. if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
  3174. E->getSourceRange(), ExprKind))
  3175. return true;
  3176. if (ExprKind == UETT_SizeOf) {
  3177. if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  3178. if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
  3179. QualType OType = PVD->getOriginalType();
  3180. QualType Type = PVD->getType();
  3181. if (Type->isPointerType() && OType->isArrayType()) {
  3182. Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
  3183. << Type << OType;
  3184. Diag(PVD->getLocation(), diag::note_declared_at);
  3185. }
  3186. }
  3187. }
  3188. // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
  3189. // decays into a pointer and returns an unintended result. This is most
  3190. // likely a typo for "sizeof(array) op x".
  3191. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
  3192. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3193. BO->getLHS());
  3194. warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
  3195. BO->getRHS());
  3196. }
  3197. }
  3198. return false;
  3199. }
  3200. /// \brief Check the constraints on operands to unary expression and type
  3201. /// traits.
  3202. ///
  3203. /// This will complete any types necessary, and validate the various constraints
  3204. /// on those operands.
  3205. ///
  3206. /// The UsualUnaryConversions() function is *not* called by this routine.
  3207. /// C99 6.3.2.1p[2-4] all state:
  3208. /// Except when it is the operand of the sizeof operator ...
  3209. ///
  3210. /// C++ [expr.sizeof]p4
  3211. /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
  3212. /// standard conversions are not applied to the operand of sizeof.
  3213. ///
  3214. /// This policy is followed for all of the unary trait expressions.
  3215. bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
  3216. SourceLocation OpLoc,
  3217. SourceRange ExprRange,
  3218. UnaryExprOrTypeTrait ExprKind) {
  3219. if (ExprType->isDependentType())
  3220. return false;
  3221. // C++ [expr.sizeof]p2:
  3222. // When applied to a reference or a reference type, the result
  3223. // is the size of the referenced type.
  3224. // C++11 [expr.alignof]p3:
  3225. // When alignof is applied to a reference type, the result
  3226. // shall be the alignment of the referenced type.
  3227. if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
  3228. ExprType = Ref->getPointeeType();
  3229. // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
  3230. // When alignof or _Alignof is applied to an array type, the result
  3231. // is the alignment of the element type.
  3232. if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
  3233. ExprType = Context.getBaseElementType(ExprType);
  3234. if (ExprKind == UETT_VecStep)
  3235. return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
  3236. // Whitelist some types as extensions
  3237. if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
  3238. ExprKind))
  3239. return false;
  3240. if (RequireCompleteType(OpLoc, ExprType,
  3241. diag::err_sizeof_alignof_incomplete_type,
  3242. ExprKind, ExprRange))
  3243. return true;
  3244. if (ExprType->isFunctionType()) {
  3245. Diag(OpLoc, diag::err_sizeof_alignof_function_type)
  3246. << ExprKind << ExprRange;
  3247. return true;
  3248. }
  3249. if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
  3250. ExprKind))
  3251. return true;
  3252. return false;
  3253. }
  3254. static bool CheckAlignOfExpr(Sema &S, Expr *E) {
  3255. E = E->IgnoreParens();
  3256. // Cannot know anything else if the expression is dependent.
  3257. if (E->isTypeDependent())
  3258. return false;
  3259. if (E->getObjectKind() == OK_BitField) {
  3260. S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
  3261. << 1 << E->getSourceRange();
  3262. return true;
  3263. }
  3264. ValueDecl *D = nullptr;
  3265. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  3266. D = DRE->getDecl();
  3267. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  3268. D = ME->getMemberDecl();
  3269. }
  3270. // If it's a field, require the containing struct to have a
  3271. // complete definition so that we can compute the layout.
  3272. //
  3273. // This can happen in C++11 onwards, either by naming the member
  3274. // in a way that is not transformed into a member access expression
  3275. // (in an unevaluated operand, for instance), or by naming the member
  3276. // in a trailing-return-type.
  3277. //
  3278. // For the record, since __alignof__ on expressions is a GCC
  3279. // extension, GCC seems to permit this but always gives the
  3280. // nonsensical answer 0.
  3281. //
  3282. // We don't really need the layout here --- we could instead just
  3283. // directly check for all the appropriate alignment-lowing
  3284. // attributes --- but that would require duplicating a lot of
  3285. // logic that just isn't worth duplicating for such a marginal
  3286. // use-case.
  3287. if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
  3288. // Fast path this check, since we at least know the record has a
  3289. // definition if we can find a member of it.
  3290. if (!FD->getParent()->isCompleteDefinition()) {
  3291. S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
  3292. << E->getSourceRange();
  3293. return true;
  3294. }
  3295. // Otherwise, if it's a field, and the field doesn't have
  3296. // reference type, then it must have a complete type (or be a
  3297. // flexible array member, which we explicitly want to
  3298. // white-list anyway), which makes the following checks trivial.
  3299. if (!FD->getType()->isReferenceType())
  3300. return false;
  3301. }
  3302. return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
  3303. }
  3304. bool Sema::CheckVecStepExpr(Expr *E) {
  3305. E = E->IgnoreParens();
  3306. // Cannot know anything else if the expression is dependent.
  3307. if (E->isTypeDependent())
  3308. return false;
  3309. return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
  3310. }
  3311. static void captureVariablyModifiedType(ASTContext &Context, QualType T,
  3312. CapturingScopeInfo *CSI) {
  3313. assert(T->isVariablyModifiedType());
  3314. assert(CSI != nullptr);
  3315. // We're going to walk down into the type and look for VLA expressions.
  3316. do {
  3317. const Type *Ty = T.getTypePtr();
  3318. switch (Ty->getTypeClass()) {
  3319. #define TYPE(Class, Base)
  3320. #define ABSTRACT_TYPE(Class, Base)
  3321. #define NON_CANONICAL_TYPE(Class, Base)
  3322. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  3323. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  3324. #include "clang/AST/TypeNodes.def"
  3325. T = QualType();
  3326. break;
  3327. // These types are never variably-modified.
  3328. case Type::Builtin:
  3329. case Type::Complex:
  3330. case Type::Vector:
  3331. case Type::ExtVector:
  3332. case Type::Record:
  3333. case Type::Enum:
  3334. case Type::Elaborated:
  3335. case Type::TemplateSpecialization:
  3336. case Type::ObjCObject:
  3337. case Type::ObjCInterface:
  3338. case Type::ObjCObjectPointer:
  3339. case Type::ObjCTypeParam:
  3340. case Type::Pipe:
  3341. llvm_unreachable("type class is never variably-modified!");
  3342. case Type::Adjusted:
  3343. T = cast<AdjustedType>(Ty)->getOriginalType();
  3344. break;
  3345. case Type::Decayed:
  3346. T = cast<DecayedType>(Ty)->getPointeeType();
  3347. break;
  3348. case Type::Pointer:
  3349. T = cast<PointerType>(Ty)->getPointeeType();
  3350. break;
  3351. case Type::BlockPointer:
  3352. T = cast<BlockPointerType>(Ty)->getPointeeType();
  3353. break;
  3354. case Type::LValueReference:
  3355. case Type::RValueReference:
  3356. T = cast<ReferenceType>(Ty)->getPointeeType();
  3357. break;
  3358. case Type::MemberPointer:
  3359. T = cast<MemberPointerType>(Ty)->getPointeeType();
  3360. break;
  3361. case Type::ConstantArray:
  3362. case Type::IncompleteArray:
  3363. // Losing element qualification here is fine.
  3364. T = cast<ArrayType>(Ty)->getElementType();
  3365. break;
  3366. case Type::VariableArray: {
  3367. // Losing element qualification here is fine.
  3368. const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
  3369. // Unknown size indication requires no size computation.
  3370. // Otherwise, evaluate and record it.
  3371. if (auto Size = VAT->getSizeExpr()) {
  3372. if (!CSI->isVLATypeCaptured(VAT)) {
  3373. RecordDecl *CapRecord = nullptr;
  3374. if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
  3375. CapRecord = LSI->Lambda;
  3376. } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  3377. CapRecord = CRSI->TheRecordDecl;
  3378. }
  3379. if (CapRecord) {
  3380. auto ExprLoc = Size->getExprLoc();
  3381. auto SizeType = Context.getSizeType();
  3382. // Build the non-static data member.
  3383. auto Field =
  3384. FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
  3385. /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
  3386. /*BW*/ nullptr, /*Mutable*/ false,
  3387. /*InitStyle*/ ICIS_NoInit);
  3388. Field->setImplicit(true);
  3389. Field->setAccess(AS_private);
  3390. Field->setCapturedVLAType(VAT);
  3391. CapRecord->addDecl(Field);
  3392. CSI->addVLATypeCapture(ExprLoc, SizeType);
  3393. }
  3394. }
  3395. }
  3396. T = VAT->getElementType();
  3397. break;
  3398. }
  3399. case Type::FunctionProto:
  3400. case Type::FunctionNoProto:
  3401. T = cast<FunctionType>(Ty)->getReturnType();
  3402. break;
  3403. case Type::Paren:
  3404. case Type::TypeOf:
  3405. case Type::UnaryTransform:
  3406. case Type::Attributed:
  3407. case Type::SubstTemplateTypeParm:
  3408. case Type::PackExpansion:
  3409. // Keep walking after single level desugaring.
  3410. T = T.getSingleStepDesugaredType(Context);
  3411. break;
  3412. case Type::Typedef:
  3413. T = cast<TypedefType>(Ty)->desugar();
  3414. break;
  3415. case Type::Decltype:
  3416. T = cast<DecltypeType>(Ty)->desugar();
  3417. break;
  3418. case Type::Auto:
  3419. case Type::DeducedTemplateSpecialization:
  3420. T = cast<DeducedType>(Ty)->getDeducedType();
  3421. break;
  3422. case Type::TypeOfExpr:
  3423. T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
  3424. break;
  3425. case Type::Atomic:
  3426. T = cast<AtomicType>(Ty)->getValueType();
  3427. break;
  3428. }
  3429. } while (!T.isNull() && T->isVariablyModifiedType());
  3430. }
  3431. /// \brief Build a sizeof or alignof expression given a type operand.
  3432. ExprResult
  3433. Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
  3434. SourceLocation OpLoc,
  3435. UnaryExprOrTypeTrait ExprKind,
  3436. SourceRange R) {
  3437. if (!TInfo)
  3438. return ExprError();
  3439. QualType T = TInfo->getType();
  3440. if (!T->isDependentType() &&
  3441. CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
  3442. return ExprError();
  3443. if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
  3444. if (auto *TT = T->getAs<TypedefType>()) {
  3445. for (auto I = FunctionScopes.rbegin(),
  3446. E = std::prev(FunctionScopes.rend());
  3447. I != E; ++I) {
  3448. auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
  3449. if (CSI == nullptr)
  3450. break;
  3451. DeclContext *DC = nullptr;
  3452. if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
  3453. DC = LSI->CallOperator;
  3454. else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
  3455. DC = CRSI->TheCapturedDecl;
  3456. else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
  3457. DC = BSI->TheDecl;
  3458. if (DC) {
  3459. if (DC->containsDecl(TT->getDecl()))
  3460. break;
  3461. captureVariablyModifiedType(Context, T, CSI);
  3462. }
  3463. }
  3464. }
  3465. }
  3466. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3467. return new (Context) UnaryExprOrTypeTraitExpr(
  3468. ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
  3469. }
  3470. /// \brief Build a sizeof or alignof expression given an expression
  3471. /// operand.
  3472. ExprResult
  3473. Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
  3474. UnaryExprOrTypeTrait ExprKind) {
  3475. ExprResult PE = CheckPlaceholderExpr(E);
  3476. if (PE.isInvalid())
  3477. return ExprError();
  3478. E = PE.get();
  3479. // Verify that the operand is valid.
  3480. bool isInvalid = false;
  3481. if (E->isTypeDependent()) {
  3482. // Delay type-checking for type-dependent expressions.
  3483. } else if (ExprKind == UETT_AlignOf) {
  3484. isInvalid = CheckAlignOfExpr(*this, E);
  3485. } else if (ExprKind == UETT_VecStep) {
  3486. isInvalid = CheckVecStepExpr(E);
  3487. } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
  3488. Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
  3489. isInvalid = true;
  3490. } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
  3491. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
  3492. isInvalid = true;
  3493. } else {
  3494. isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
  3495. }
  3496. if (isInvalid)
  3497. return ExprError();
  3498. if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
  3499. PE = TransformToPotentiallyEvaluated(E);
  3500. if (PE.isInvalid()) return ExprError();
  3501. E = PE.get();
  3502. }
  3503. // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
  3504. return new (Context) UnaryExprOrTypeTraitExpr(
  3505. ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
  3506. }
  3507. /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
  3508. /// expr and the same for @c alignof and @c __alignof
  3509. /// Note that the ArgRange is invalid if isType is false.
  3510. ExprResult
  3511. Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
  3512. UnaryExprOrTypeTrait ExprKind, bool IsType,
  3513. void *TyOrEx, SourceRange ArgRange) {
  3514. // If error parsing type, ignore.
  3515. if (!TyOrEx) return ExprError();
  3516. if (IsType) {
  3517. TypeSourceInfo *TInfo;
  3518. (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
  3519. return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
  3520. }
  3521. Expr *ArgEx = (Expr *)TyOrEx;
  3522. ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
  3523. return Result;
  3524. }
  3525. static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
  3526. bool IsReal) {
  3527. if (V.get()->isTypeDependent())
  3528. return S.Context.DependentTy;
  3529. // _Real and _Imag are only l-values for normal l-values.
  3530. if (V.get()->getObjectKind() != OK_Ordinary) {
  3531. V = S.DefaultLvalueConversion(V.get());
  3532. if (V.isInvalid())
  3533. return QualType();
  3534. }
  3535. // These operators return the element type of a complex type.
  3536. if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
  3537. return CT->getElementType();
  3538. // Otherwise they pass through real integer and floating point types here.
  3539. if (V.get()->getType()->isArithmeticType())
  3540. return V.get()->getType();
  3541. // Test for placeholders.
  3542. ExprResult PR = S.CheckPlaceholderExpr(V.get());
  3543. if (PR.isInvalid()) return QualType();
  3544. if (PR.get() != V.get()) {
  3545. V = PR;
  3546. return CheckRealImagOperand(S, V, Loc, IsReal);
  3547. }
  3548. // Reject anything else.
  3549. S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
  3550. << (IsReal ? "__real" : "__imag");
  3551. return QualType();
  3552. }
  3553. ExprResult
  3554. Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
  3555. tok::TokenKind Kind, Expr *Input) {
  3556. UnaryOperatorKind Opc;
  3557. switch (Kind) {
  3558. default: llvm_unreachable("Unknown unary op!");
  3559. case tok::plusplus: Opc = UO_PostInc; break;
  3560. case tok::minusminus: Opc = UO_PostDec; break;
  3561. }
  3562. // Since this might is a postfix expression, get rid of ParenListExprs.
  3563. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
  3564. if (Result.isInvalid()) return ExprError();
  3565. Input = Result.get();
  3566. return BuildUnaryOp(S, OpLoc, Opc, Input);
  3567. }
  3568. /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
  3569. ///
  3570. /// \return true on error
  3571. static bool checkArithmeticOnObjCPointer(Sema &S,
  3572. SourceLocation opLoc,
  3573. Expr *op) {
  3574. assert(op->getType()->isObjCObjectPointerType());
  3575. if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
  3576. !S.LangOpts.ObjCSubscriptingLegacyRuntime)
  3577. return false;
  3578. S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
  3579. << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
  3580. << op->getSourceRange();
  3581. return true;
  3582. }
  3583. static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
  3584. auto *BaseNoParens = Base->IgnoreParens();
  3585. if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
  3586. return MSProp->getPropertyDecl()->getType()->isArrayType();
  3587. return isa<MSPropertySubscriptExpr>(BaseNoParens);
  3588. }
  3589. ExprResult
  3590. Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
  3591. Expr *idx, SourceLocation rbLoc) {
  3592. if (base && !base->getType().isNull() &&
  3593. base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
  3594. return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
  3595. /*Length=*/nullptr, rbLoc);
  3596. // Since this might be a postfix expression, get rid of ParenListExprs.
  3597. if (isa<ParenListExpr>(base)) {
  3598. ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
  3599. if (result.isInvalid()) return ExprError();
  3600. base = result.get();
  3601. }
  3602. // Handle any non-overload placeholder types in the base and index
  3603. // expressions. We can't handle overloads here because the other
  3604. // operand might be an overloadable type, in which case the overload
  3605. // resolution for the operator overload should get the first crack
  3606. // at the overload.
  3607. bool IsMSPropertySubscript = false;
  3608. if (base->getType()->isNonOverloadPlaceholderType()) {
  3609. IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
  3610. if (!IsMSPropertySubscript) {
  3611. ExprResult result = CheckPlaceholderExpr(base);
  3612. if (result.isInvalid())
  3613. return ExprError();
  3614. base = result.get();
  3615. }
  3616. }
  3617. if (idx->getType()->isNonOverloadPlaceholderType()) {
  3618. ExprResult result = CheckPlaceholderExpr(idx);
  3619. if (result.isInvalid()) return ExprError();
  3620. idx = result.get();
  3621. }
  3622. // Build an unanalyzed expression if either operand is type-dependent.
  3623. if (getLangOpts().CPlusPlus &&
  3624. (base->isTypeDependent() || idx->isTypeDependent())) {
  3625. return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
  3626. VK_LValue, OK_Ordinary, rbLoc);
  3627. }
  3628. // MSDN, property (C++)
  3629. // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
  3630. // This attribute can also be used in the declaration of an empty array in a
  3631. // class or structure definition. For example:
  3632. // __declspec(property(get=GetX, put=PutX)) int x[];
  3633. // The above statement indicates that x[] can be used with one or more array
  3634. // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
  3635. // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
  3636. if (IsMSPropertySubscript) {
  3637. // Build MS property subscript expression if base is MS property reference
  3638. // or MS property subscript.
  3639. return new (Context) MSPropertySubscriptExpr(
  3640. base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
  3641. }
  3642. // Use C++ overloaded-operator rules if either operand has record
  3643. // type. The spec says to do this if either type is *overloadable*,
  3644. // but enum types can't declare subscript operators or conversion
  3645. // operators, so there's nothing interesting for overload resolution
  3646. // to do if there aren't any record types involved.
  3647. //
  3648. // ObjC pointers have their own subscripting logic that is not tied
  3649. // to overload resolution and so should not take this path.
  3650. if (getLangOpts().CPlusPlus &&
  3651. (base->getType()->isRecordType() ||
  3652. (!base->getType()->isObjCObjectPointerType() &&
  3653. idx->getType()->isRecordType()))) {
  3654. return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
  3655. }
  3656. return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
  3657. }
  3658. ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
  3659. Expr *LowerBound,
  3660. SourceLocation ColonLoc, Expr *Length,
  3661. SourceLocation RBLoc) {
  3662. if (Base->getType()->isPlaceholderType() &&
  3663. !Base->getType()->isSpecificPlaceholderType(
  3664. BuiltinType::OMPArraySection)) {
  3665. ExprResult Result = CheckPlaceholderExpr(Base);
  3666. if (Result.isInvalid())
  3667. return ExprError();
  3668. Base = Result.get();
  3669. }
  3670. if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
  3671. ExprResult Result = CheckPlaceholderExpr(LowerBound);
  3672. if (Result.isInvalid())
  3673. return ExprError();
  3674. Result = DefaultLvalueConversion(Result.get());
  3675. if (Result.isInvalid())
  3676. return ExprError();
  3677. LowerBound = Result.get();
  3678. }
  3679. if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
  3680. ExprResult Result = CheckPlaceholderExpr(Length);
  3681. if (Result.isInvalid())
  3682. return ExprError();
  3683. Result = DefaultLvalueConversion(Result.get());
  3684. if (Result.isInvalid())
  3685. return ExprError();
  3686. Length = Result.get();
  3687. }
  3688. // Build an unanalyzed expression if either operand is type-dependent.
  3689. if (Base->isTypeDependent() ||
  3690. (LowerBound &&
  3691. (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
  3692. (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
  3693. return new (Context)
  3694. OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
  3695. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3696. }
  3697. // Perform default conversions.
  3698. QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
  3699. QualType ResultTy;
  3700. if (OriginalTy->isAnyPointerType()) {
  3701. ResultTy = OriginalTy->getPointeeType();
  3702. } else if (OriginalTy->isArrayType()) {
  3703. ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
  3704. } else {
  3705. return ExprError(
  3706. Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
  3707. << Base->getSourceRange());
  3708. }
  3709. // C99 6.5.2.1p1
  3710. if (LowerBound) {
  3711. auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
  3712. LowerBound);
  3713. if (Res.isInvalid())
  3714. return ExprError(Diag(LowerBound->getExprLoc(),
  3715. diag::err_omp_typecheck_section_not_integer)
  3716. << 0 << LowerBound->getSourceRange());
  3717. LowerBound = Res.get();
  3718. if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3719. LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3720. Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
  3721. << 0 << LowerBound->getSourceRange();
  3722. }
  3723. if (Length) {
  3724. auto Res =
  3725. PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
  3726. if (Res.isInvalid())
  3727. return ExprError(Diag(Length->getExprLoc(),
  3728. diag::err_omp_typecheck_section_not_integer)
  3729. << 1 << Length->getSourceRange());
  3730. Length = Res.get();
  3731. if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3732. Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3733. Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
  3734. << 1 << Length->getSourceRange();
  3735. }
  3736. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3737. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3738. // type. Note that functions are not objects, and that (in C99 parlance)
  3739. // incomplete types are not object types.
  3740. if (ResultTy->isFunctionType()) {
  3741. Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
  3742. << ResultTy << Base->getSourceRange();
  3743. return ExprError();
  3744. }
  3745. if (RequireCompleteType(Base->getExprLoc(), ResultTy,
  3746. diag::err_omp_section_incomplete_type, Base))
  3747. return ExprError();
  3748. if (LowerBound && !OriginalTy->isAnyPointerType()) {
  3749. llvm::APSInt LowerBoundValue;
  3750. if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
  3751. // OpenMP 4.5, [2.4 Array Sections]
  3752. // The array section must be a subset of the original array.
  3753. if (LowerBoundValue.isNegative()) {
  3754. Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
  3755. << LowerBound->getSourceRange();
  3756. return ExprError();
  3757. }
  3758. }
  3759. }
  3760. if (Length) {
  3761. llvm::APSInt LengthValue;
  3762. if (Length->EvaluateAsInt(LengthValue, Context)) {
  3763. // OpenMP 4.5, [2.4 Array Sections]
  3764. // The length must evaluate to non-negative integers.
  3765. if (LengthValue.isNegative()) {
  3766. Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
  3767. << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
  3768. << Length->getSourceRange();
  3769. return ExprError();
  3770. }
  3771. }
  3772. } else if (ColonLoc.isValid() &&
  3773. (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
  3774. !OriginalTy->isVariableArrayType()))) {
  3775. // OpenMP 4.5, [2.4 Array Sections]
  3776. // When the size of the array dimension is not known, the length must be
  3777. // specified explicitly.
  3778. Diag(ColonLoc, diag::err_omp_section_length_undefined)
  3779. << (!OriginalTy.isNull() && OriginalTy->isArrayType());
  3780. return ExprError();
  3781. }
  3782. if (!Base->getType()->isSpecificPlaceholderType(
  3783. BuiltinType::OMPArraySection)) {
  3784. ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
  3785. if (Result.isInvalid())
  3786. return ExprError();
  3787. Base = Result.get();
  3788. }
  3789. return new (Context)
  3790. OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
  3791. VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
  3792. }
  3793. ExprResult
  3794. Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
  3795. Expr *Idx, SourceLocation RLoc) {
  3796. Expr *LHSExp = Base;
  3797. Expr *RHSExp = Idx;
  3798. ExprValueKind VK = VK_LValue;
  3799. ExprObjectKind OK = OK_Ordinary;
  3800. // Per C++ core issue 1213, the result is an xvalue if either operand is
  3801. // a non-lvalue array, and an lvalue otherwise.
  3802. if (getLangOpts().CPlusPlus11 &&
  3803. ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
  3804. (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
  3805. VK = VK_XValue;
  3806. // Perform default conversions.
  3807. if (!LHSExp->getType()->getAs<VectorType>()) {
  3808. ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
  3809. if (Result.isInvalid())
  3810. return ExprError();
  3811. LHSExp = Result.get();
  3812. }
  3813. ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
  3814. if (Result.isInvalid())
  3815. return ExprError();
  3816. RHSExp = Result.get();
  3817. QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
  3818. // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
  3819. // to the expression *((e1)+(e2)). This means the array "Base" may actually be
  3820. // in the subscript position. As a result, we need to derive the array base
  3821. // and index from the expression types.
  3822. Expr *BaseExpr, *IndexExpr;
  3823. QualType ResultType;
  3824. if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
  3825. BaseExpr = LHSExp;
  3826. IndexExpr = RHSExp;
  3827. ResultType = Context.DependentTy;
  3828. } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
  3829. BaseExpr = LHSExp;
  3830. IndexExpr = RHSExp;
  3831. ResultType = PTy->getPointeeType();
  3832. } else if (const ObjCObjectPointerType *PTy =
  3833. LHSTy->getAs<ObjCObjectPointerType>()) {
  3834. BaseExpr = LHSExp;
  3835. IndexExpr = RHSExp;
  3836. // Use custom logic if this should be the pseudo-object subscript
  3837. // expression.
  3838. if (!LangOpts.isSubscriptPointerArithmetic())
  3839. return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
  3840. nullptr);
  3841. ResultType = PTy->getPointeeType();
  3842. } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
  3843. // Handle the uncommon case of "123[Ptr]".
  3844. BaseExpr = RHSExp;
  3845. IndexExpr = LHSExp;
  3846. ResultType = PTy->getPointeeType();
  3847. } else if (const ObjCObjectPointerType *PTy =
  3848. RHSTy->getAs<ObjCObjectPointerType>()) {
  3849. // Handle the uncommon case of "123[Ptr]".
  3850. BaseExpr = RHSExp;
  3851. IndexExpr = LHSExp;
  3852. ResultType = PTy->getPointeeType();
  3853. if (!LangOpts.isSubscriptPointerArithmetic()) {
  3854. Diag(LLoc, diag::err_subscript_nonfragile_interface)
  3855. << ResultType << BaseExpr->getSourceRange();
  3856. return ExprError();
  3857. }
  3858. } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
  3859. BaseExpr = LHSExp; // vectors: V[123]
  3860. IndexExpr = RHSExp;
  3861. VK = LHSExp->getValueKind();
  3862. if (VK != VK_RValue)
  3863. OK = OK_VectorComponent;
  3864. // FIXME: need to deal with const...
  3865. ResultType = VTy->getElementType();
  3866. } else if (LHSTy->isArrayType()) {
  3867. // If we see an array that wasn't promoted by
  3868. // DefaultFunctionArrayLvalueConversion, it must be an array that
  3869. // wasn't promoted because of the C90 rule that doesn't
  3870. // allow promoting non-lvalue arrays. Warn, then
  3871. // force the promotion here.
  3872. Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3873. LHSExp->getSourceRange();
  3874. LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
  3875. CK_ArrayToPointerDecay).get();
  3876. LHSTy = LHSExp->getType();
  3877. BaseExpr = LHSExp;
  3878. IndexExpr = RHSExp;
  3879. ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
  3880. } else if (RHSTy->isArrayType()) {
  3881. // Same as previous, except for 123[f().a] case
  3882. Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
  3883. RHSExp->getSourceRange();
  3884. RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
  3885. CK_ArrayToPointerDecay).get();
  3886. RHSTy = RHSExp->getType();
  3887. BaseExpr = RHSExp;
  3888. IndexExpr = LHSExp;
  3889. ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
  3890. } else {
  3891. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
  3892. << LHSExp->getSourceRange() << RHSExp->getSourceRange());
  3893. }
  3894. // C99 6.5.2.1p1
  3895. if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
  3896. return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
  3897. << IndexExpr->getSourceRange());
  3898. if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
  3899. IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
  3900. && !IndexExpr->isTypeDependent())
  3901. Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
  3902. // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
  3903. // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
  3904. // type. Note that Functions are not objects, and that (in C99 parlance)
  3905. // incomplete types are not object types.
  3906. if (ResultType->isFunctionType()) {
  3907. Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
  3908. << ResultType << BaseExpr->getSourceRange();
  3909. return ExprError();
  3910. }
  3911. if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
  3912. // GNU extension: subscripting on pointer to void
  3913. Diag(LLoc, diag::ext_gnu_subscript_void_type)
  3914. << BaseExpr->getSourceRange();
  3915. // C forbids expressions of unqualified void type from being l-values.
  3916. // See IsCForbiddenLValueType.
  3917. if (!ResultType.hasQualifiers()) VK = VK_RValue;
  3918. } else if (!ResultType->isDependentType() &&
  3919. RequireCompleteType(LLoc, ResultType,
  3920. diag::err_subscript_incomplete_type, BaseExpr))
  3921. return ExprError();
  3922. assert(VK == VK_RValue || LangOpts.CPlusPlus ||
  3923. !ResultType.isCForbiddenLValueType());
  3924. return new (Context)
  3925. ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
  3926. }
  3927. bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
  3928. ParmVarDecl *Param) {
  3929. if (Param->hasUnparsedDefaultArg()) {
  3930. Diag(CallLoc,
  3931. diag::err_use_of_default_argument_to_function_declared_later) <<
  3932. FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
  3933. Diag(UnparsedDefaultArgLocs[Param],
  3934. diag::note_default_argument_declared_here);
  3935. return true;
  3936. }
  3937. if (Param->hasUninstantiatedDefaultArg()) {
  3938. Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
  3939. EnterExpressionEvaluationContext EvalContext(
  3940. *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
  3941. // Instantiate the expression.
  3942. //
  3943. // FIXME: Pass in a correct Pattern argument, otherwise
  3944. // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
  3945. //
  3946. // template<typename T>
  3947. // struct A {
  3948. // static int FooImpl();
  3949. //
  3950. // template<typename Tp>
  3951. // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
  3952. // // template argument list [[T], [Tp]], should be [[Tp]].
  3953. // friend A<Tp> Foo(int a);
  3954. // };
  3955. //
  3956. // template<typename T>
  3957. // A<T> Foo(int a = A<T>::FooImpl());
  3958. MultiLevelTemplateArgumentList MutiLevelArgList
  3959. = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
  3960. InstantiatingTemplate Inst(*this, CallLoc, Param,
  3961. MutiLevelArgList.getInnermost());
  3962. if (Inst.isInvalid())
  3963. return true;
  3964. if (Inst.isAlreadyInstantiating()) {
  3965. Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
  3966. Param->setInvalidDecl();
  3967. return true;
  3968. }
  3969. ExprResult Result;
  3970. {
  3971. // C++ [dcl.fct.default]p5:
  3972. // The names in the [default argument] expression are bound, and
  3973. // the semantic constraints are checked, at the point where the
  3974. // default argument expression appears.
  3975. ContextRAII SavedContext(*this, FD);
  3976. LocalInstantiationScope Local(*this);
  3977. Result = SubstInitializer(UninstExpr, MutiLevelArgList,
  3978. /*DirectInit*/false);
  3979. }
  3980. if (Result.isInvalid())
  3981. return true;
  3982. // Check the expression as an initializer for the parameter.
  3983. InitializedEntity Entity
  3984. = InitializedEntity::InitializeParameter(Context, Param);
  3985. InitializationKind Kind
  3986. = InitializationKind::CreateCopy(Param->getLocation(),
  3987. /*FIXME:EqualLoc*/UninstExpr->getLocStart());
  3988. Expr *ResultE = Result.getAs<Expr>();
  3989. InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
  3990. Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
  3991. if (Result.isInvalid())
  3992. return true;
  3993. Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
  3994. Param->getOuterLocStart());
  3995. if (Result.isInvalid())
  3996. return true;
  3997. // Remember the instantiated default argument.
  3998. Param->setDefaultArg(Result.getAs<Expr>());
  3999. if (ASTMutationListener *L = getASTMutationListener()) {
  4000. L->DefaultArgumentInstantiated(Param);
  4001. }
  4002. }
  4003. // If the default argument expression is not set yet, we are building it now.
  4004. if (!Param->hasInit()) {
  4005. Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
  4006. Param->setInvalidDecl();
  4007. return true;
  4008. }
  4009. // If the default expression creates temporaries, we need to
  4010. // push them to the current stack of expression temporaries so they'll
  4011. // be properly destroyed.
  4012. // FIXME: We should really be rebuilding the default argument with new
  4013. // bound temporaries; see the comment in PR5810.
  4014. // We don't need to do that with block decls, though, because
  4015. // blocks in default argument expression can never capture anything.
  4016. if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
  4017. // Set the "needs cleanups" bit regardless of whether there are
  4018. // any explicit objects.
  4019. Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
  4020. // Append all the objects to the cleanup list. Right now, this
  4021. // should always be a no-op, because blocks in default argument
  4022. // expressions should never be able to capture anything.
  4023. assert(!Init->getNumObjects() &&
  4024. "default argument expression has capturing blocks?");
  4025. }
  4026. // We already type-checked the argument, so we know it works.
  4027. // Just mark all of the declarations in this potentially-evaluated expression
  4028. // as being "referenced".
  4029. MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
  4030. /*SkipLocalVariables=*/true);
  4031. return false;
  4032. }
  4033. ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
  4034. FunctionDecl *FD, ParmVarDecl *Param) {
  4035. if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
  4036. return ExprError();
  4037. return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
  4038. }
  4039. Sema::VariadicCallType
  4040. Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
  4041. Expr *Fn) {
  4042. if (Proto && Proto->isVariadic()) {
  4043. if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
  4044. return VariadicConstructor;
  4045. else if (Fn && Fn->getType()->isBlockPointerType())
  4046. return VariadicBlock;
  4047. else if (FDecl) {
  4048. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4049. if (Method->isInstance())
  4050. return VariadicMethod;
  4051. } else if (Fn && Fn->getType() == Context.BoundMemberTy)
  4052. return VariadicMethod;
  4053. return VariadicFunction;
  4054. }
  4055. return VariadicDoesNotApply;
  4056. }
  4057. namespace {
  4058. class FunctionCallCCC : public FunctionCallFilterCCC {
  4059. public:
  4060. FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
  4061. unsigned NumArgs, MemberExpr *ME)
  4062. : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
  4063. FunctionName(FuncName) {}
  4064. bool ValidateCandidate(const TypoCorrection &candidate) override {
  4065. if (!candidate.getCorrectionSpecifier() ||
  4066. candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
  4067. return false;
  4068. }
  4069. return FunctionCallFilterCCC::ValidateCandidate(candidate);
  4070. }
  4071. private:
  4072. const IdentifierInfo *const FunctionName;
  4073. };
  4074. }
  4075. static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
  4076. FunctionDecl *FDecl,
  4077. ArrayRef<Expr *> Args) {
  4078. MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
  4079. DeclarationName FuncName = FDecl->getDeclName();
  4080. SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
  4081. if (TypoCorrection Corrected = S.CorrectTypo(
  4082. DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
  4083. S.getScopeForContext(S.CurContext), nullptr,
  4084. llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
  4085. Args.size(), ME),
  4086. Sema::CTK_ErrorRecovery)) {
  4087. if (NamedDecl *ND = Corrected.getFoundDecl()) {
  4088. if (Corrected.isOverloaded()) {
  4089. OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
  4090. OverloadCandidateSet::iterator Best;
  4091. for (NamedDecl *CD : Corrected) {
  4092. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
  4093. S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
  4094. OCS);
  4095. }
  4096. switch (OCS.BestViableFunction(S, NameLoc, Best)) {
  4097. case OR_Success:
  4098. ND = Best->FoundDecl;
  4099. Corrected.setCorrectionDecl(ND);
  4100. break;
  4101. default:
  4102. break;
  4103. }
  4104. }
  4105. ND = ND->getUnderlyingDecl();
  4106. if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
  4107. return Corrected;
  4108. }
  4109. }
  4110. return TypoCorrection();
  4111. }
  4112. /// ConvertArgumentsForCall - Converts the arguments specified in
  4113. /// Args/NumArgs to the parameter types of the function FDecl with
  4114. /// function prototype Proto. Call is the call expression itself, and
  4115. /// Fn is the function expression. For a C++ member function, this
  4116. /// routine does not attempt to convert the object argument. Returns
  4117. /// true if the call is ill-formed.
  4118. bool
  4119. Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
  4120. FunctionDecl *FDecl,
  4121. const FunctionProtoType *Proto,
  4122. ArrayRef<Expr *> Args,
  4123. SourceLocation RParenLoc,
  4124. bool IsExecConfig) {
  4125. // Bail out early if calling a builtin with custom typechecking.
  4126. if (FDecl)
  4127. if (unsigned ID = FDecl->getBuiltinID())
  4128. if (Context.BuiltinInfo.hasCustomTypechecking(ID))
  4129. return false;
  4130. // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
  4131. // assignment, to the types of the corresponding parameter, ...
  4132. unsigned NumParams = Proto->getNumParams();
  4133. bool Invalid = false;
  4134. unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
  4135. unsigned FnKind = Fn->getType()->isBlockPointerType()
  4136. ? 1 /* block */
  4137. : (IsExecConfig ? 3 /* kernel function (exec config) */
  4138. : 0 /* function */);
  4139. // If too few arguments are available (and we don't have default
  4140. // arguments for the remaining parameters), don't make the call.
  4141. if (Args.size() < NumParams) {
  4142. if (Args.size() < MinArgs) {
  4143. TypoCorrection TC;
  4144. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4145. unsigned diag_id =
  4146. MinArgs == NumParams && !Proto->isVariadic()
  4147. ? diag::err_typecheck_call_too_few_args_suggest
  4148. : diag::err_typecheck_call_too_few_args_at_least_suggest;
  4149. diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
  4150. << static_cast<unsigned>(Args.size())
  4151. << TC.getCorrectionRange());
  4152. } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
  4153. Diag(RParenLoc,
  4154. MinArgs == NumParams && !Proto->isVariadic()
  4155. ? diag::err_typecheck_call_too_few_args_one
  4156. : diag::err_typecheck_call_too_few_args_at_least_one)
  4157. << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
  4158. else
  4159. Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
  4160. ? diag::err_typecheck_call_too_few_args
  4161. : diag::err_typecheck_call_too_few_args_at_least)
  4162. << FnKind << MinArgs << static_cast<unsigned>(Args.size())
  4163. << Fn->getSourceRange();
  4164. // Emit the location of the prototype.
  4165. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4166. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  4167. << FDecl;
  4168. return true;
  4169. }
  4170. Call->setNumArgs(Context, NumParams);
  4171. }
  4172. // If too many are passed and not variadic, error on the extras and drop
  4173. // them.
  4174. if (Args.size() > NumParams) {
  4175. if (!Proto->isVariadic()) {
  4176. TypoCorrection TC;
  4177. if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
  4178. unsigned diag_id =
  4179. MinArgs == NumParams && !Proto->isVariadic()
  4180. ? diag::err_typecheck_call_too_many_args_suggest
  4181. : diag::err_typecheck_call_too_many_args_at_most_suggest;
  4182. diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
  4183. << static_cast<unsigned>(Args.size())
  4184. << TC.getCorrectionRange());
  4185. } else if (NumParams == 1 && FDecl &&
  4186. FDecl->getParamDecl(0)->getDeclName())
  4187. Diag(Args[NumParams]->getLocStart(),
  4188. MinArgs == NumParams
  4189. ? diag::err_typecheck_call_too_many_args_one
  4190. : diag::err_typecheck_call_too_many_args_at_most_one)
  4191. << FnKind << FDecl->getParamDecl(0)
  4192. << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
  4193. << SourceRange(Args[NumParams]->getLocStart(),
  4194. Args.back()->getLocEnd());
  4195. else
  4196. Diag(Args[NumParams]->getLocStart(),
  4197. MinArgs == NumParams
  4198. ? diag::err_typecheck_call_too_many_args
  4199. : diag::err_typecheck_call_too_many_args_at_most)
  4200. << FnKind << NumParams << static_cast<unsigned>(Args.size())
  4201. << Fn->getSourceRange()
  4202. << SourceRange(Args[NumParams]->getLocStart(),
  4203. Args.back()->getLocEnd());
  4204. // Emit the location of the prototype.
  4205. if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
  4206. Diag(FDecl->getLocStart(), diag::note_callee_decl)
  4207. << FDecl;
  4208. // This deletes the extra arguments.
  4209. Call->setNumArgs(Context, NumParams);
  4210. return true;
  4211. }
  4212. }
  4213. SmallVector<Expr *, 8> AllArgs;
  4214. VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
  4215. Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
  4216. Proto, 0, Args, AllArgs, CallType);
  4217. if (Invalid)
  4218. return true;
  4219. unsigned TotalNumArgs = AllArgs.size();
  4220. for (unsigned i = 0; i < TotalNumArgs; ++i)
  4221. Call->setArg(i, AllArgs[i]);
  4222. return false;
  4223. }
  4224. bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
  4225. const FunctionProtoType *Proto,
  4226. unsigned FirstParam, ArrayRef<Expr *> Args,
  4227. SmallVectorImpl<Expr *> &AllArgs,
  4228. VariadicCallType CallType, bool AllowExplicit,
  4229. bool IsListInitialization) {
  4230. unsigned NumParams = Proto->getNumParams();
  4231. bool Invalid = false;
  4232. size_t ArgIx = 0;
  4233. // Continue to check argument types (even if we have too few/many args).
  4234. for (unsigned i = FirstParam; i < NumParams; i++) {
  4235. QualType ProtoArgType = Proto->getParamType(i);
  4236. Expr *Arg;
  4237. ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
  4238. if (ArgIx < Args.size()) {
  4239. Arg = Args[ArgIx++];
  4240. if (RequireCompleteType(Arg->getLocStart(),
  4241. ProtoArgType,
  4242. diag::err_call_incomplete_argument, Arg))
  4243. return true;
  4244. // Strip the unbridged-cast placeholder expression off, if applicable.
  4245. bool CFAudited = false;
  4246. if (Arg->getType() == Context.ARCUnbridgedCastTy &&
  4247. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4248. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4249. Arg = stripARCUnbridgedCast(Arg);
  4250. else if (getLangOpts().ObjCAutoRefCount &&
  4251. FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
  4252. (!Param || !Param->hasAttr<CFConsumedAttr>()))
  4253. CFAudited = true;
  4254. InitializedEntity Entity =
  4255. Param ? InitializedEntity::InitializeParameter(Context, Param,
  4256. ProtoArgType)
  4257. : InitializedEntity::InitializeParameter(
  4258. Context, ProtoArgType, Proto->isParamConsumed(i));
  4259. // Remember that parameter belongs to a CF audited API.
  4260. if (CFAudited)
  4261. Entity.setParameterCFAudited();
  4262. ExprResult ArgE = PerformCopyInitialization(
  4263. Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
  4264. if (ArgE.isInvalid())
  4265. return true;
  4266. Arg = ArgE.getAs<Expr>();
  4267. } else {
  4268. assert(Param && "can't use default arguments without a known callee");
  4269. ExprResult ArgExpr =
  4270. BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
  4271. if (ArgExpr.isInvalid())
  4272. return true;
  4273. Arg = ArgExpr.getAs<Expr>();
  4274. }
  4275. // Check for array bounds violations for each argument to the call. This
  4276. // check only triggers warnings when the argument isn't a more complex Expr
  4277. // with its own checking, such as a BinaryOperator.
  4278. CheckArrayAccess(Arg);
  4279. // Check for violations of C99 static array rules (C99 6.7.5.3p7).
  4280. CheckStaticArrayArgument(CallLoc, Param, Arg);
  4281. AllArgs.push_back(Arg);
  4282. }
  4283. // If this is a variadic call, handle args passed through "...".
  4284. if (CallType != VariadicDoesNotApply) {
  4285. // Assume that extern "C" functions with variadic arguments that
  4286. // return __unknown_anytype aren't *really* variadic.
  4287. if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
  4288. FDecl->isExternC()) {
  4289. for (Expr *A : Args.slice(ArgIx)) {
  4290. QualType paramType; // ignored
  4291. ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
  4292. Invalid |= arg.isInvalid();
  4293. AllArgs.push_back(arg.get());
  4294. }
  4295. // Otherwise do argument promotion, (C99 6.5.2.2p7).
  4296. } else {
  4297. for (Expr *A : Args.slice(ArgIx)) {
  4298. ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
  4299. Invalid |= Arg.isInvalid();
  4300. AllArgs.push_back(Arg.get());
  4301. }
  4302. }
  4303. // Check for array bounds violations.
  4304. for (Expr *A : Args.slice(ArgIx))
  4305. CheckArrayAccess(A);
  4306. }
  4307. return Invalid;
  4308. }
  4309. static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
  4310. TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
  4311. if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
  4312. TL = DTL.getOriginalLoc();
  4313. if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
  4314. S.Diag(PVD->getLocation(), diag::note_callee_static_array)
  4315. << ATL.getLocalSourceRange();
  4316. }
  4317. /// CheckStaticArrayArgument - If the given argument corresponds to a static
  4318. /// array parameter, check that it is non-null, and that if it is formed by
  4319. /// array-to-pointer decay, the underlying array is sufficiently large.
  4320. ///
  4321. /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
  4322. /// array type derivation, then for each call to the function, the value of the
  4323. /// corresponding actual argument shall provide access to the first element of
  4324. /// an array with at least as many elements as specified by the size expression.
  4325. void
  4326. Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
  4327. ParmVarDecl *Param,
  4328. const Expr *ArgExpr) {
  4329. // Static array parameters are not supported in C++.
  4330. if (!Param || getLangOpts().CPlusPlus)
  4331. return;
  4332. QualType OrigTy = Param->getOriginalType();
  4333. const ArrayType *AT = Context.getAsArrayType(OrigTy);
  4334. if (!AT || AT->getSizeModifier() != ArrayType::Static)
  4335. return;
  4336. if (ArgExpr->isNullPointerConstant(Context,
  4337. Expr::NPC_NeverValueDependent)) {
  4338. Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  4339. DiagnoseCalleeStaticArrayParam(*this, Param);
  4340. return;
  4341. }
  4342. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
  4343. if (!CAT)
  4344. return;
  4345. const ConstantArrayType *ArgCAT =
  4346. Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
  4347. if (!ArgCAT)
  4348. return;
  4349. if (ArgCAT->getSize().ult(CAT->getSize())) {
  4350. Diag(CallLoc, diag::warn_static_array_too_small)
  4351. << ArgExpr->getSourceRange()
  4352. << (unsigned) ArgCAT->getSize().getZExtValue()
  4353. << (unsigned) CAT->getSize().getZExtValue();
  4354. DiagnoseCalleeStaticArrayParam(*this, Param);
  4355. }
  4356. }
  4357. /// Given a function expression of unknown-any type, try to rebuild it
  4358. /// to have a function type.
  4359. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
  4360. /// Is the given type a placeholder that we need to lower out
  4361. /// immediately during argument processing?
  4362. static bool isPlaceholderToRemoveAsArg(QualType type) {
  4363. // Placeholders are never sugared.
  4364. const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
  4365. if (!placeholder) return false;
  4366. switch (placeholder->getKind()) {
  4367. // Ignore all the non-placeholder types.
  4368. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  4369. case BuiltinType::Id:
  4370. #include "clang/Basic/OpenCLImageTypes.def"
  4371. #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
  4372. #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
  4373. #include "clang/AST/BuiltinTypes.def"
  4374. return false;
  4375. // We cannot lower out overload sets; they might validly be resolved
  4376. // by the call machinery.
  4377. case BuiltinType::Overload:
  4378. return false;
  4379. // Unbridged casts in ARC can be handled in some call positions and
  4380. // should be left in place.
  4381. case BuiltinType::ARCUnbridgedCast:
  4382. return false;
  4383. // Pseudo-objects should be converted as soon as possible.
  4384. case BuiltinType::PseudoObject:
  4385. return true;
  4386. // The debugger mode could theoretically but currently does not try
  4387. // to resolve unknown-typed arguments based on known parameter types.
  4388. case BuiltinType::UnknownAny:
  4389. return true;
  4390. // These are always invalid as call arguments and should be reported.
  4391. case BuiltinType::BoundMember:
  4392. case BuiltinType::BuiltinFn:
  4393. case BuiltinType::OMPArraySection:
  4394. return true;
  4395. }
  4396. llvm_unreachable("bad builtin type kind");
  4397. }
  4398. /// Check an argument list for placeholders that we won't try to
  4399. /// handle later.
  4400. static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
  4401. // Apply this processing to all the arguments at once instead of
  4402. // dying at the first failure.
  4403. bool hasInvalid = false;
  4404. for (size_t i = 0, e = args.size(); i != e; i++) {
  4405. if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
  4406. ExprResult result = S.CheckPlaceholderExpr(args[i]);
  4407. if (result.isInvalid()) hasInvalid = true;
  4408. else args[i] = result.get();
  4409. } else if (hasInvalid) {
  4410. (void)S.CorrectDelayedTyposInExpr(args[i]);
  4411. }
  4412. }
  4413. return hasInvalid;
  4414. }
  4415. /// If a builtin function has a pointer argument with no explicit address
  4416. /// space, then it should be able to accept a pointer to any address
  4417. /// space as input. In order to do this, we need to replace the
  4418. /// standard builtin declaration with one that uses the same address space
  4419. /// as the call.
  4420. ///
  4421. /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
  4422. /// it does not contain any pointer arguments without
  4423. /// an address space qualifer. Otherwise the rewritten
  4424. /// FunctionDecl is returned.
  4425. /// TODO: Handle pointer return types.
  4426. static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
  4427. const FunctionDecl *FDecl,
  4428. MultiExprArg ArgExprs) {
  4429. QualType DeclType = FDecl->getType();
  4430. const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
  4431. if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
  4432. !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
  4433. return nullptr;
  4434. bool NeedsNewDecl = false;
  4435. unsigned i = 0;
  4436. SmallVector<QualType, 8> OverloadParams;
  4437. for (QualType ParamType : FT->param_types()) {
  4438. // Convert array arguments to pointer to simplify type lookup.
  4439. ExprResult ArgRes =
  4440. Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
  4441. if (ArgRes.isInvalid())
  4442. return nullptr;
  4443. Expr *Arg = ArgRes.get();
  4444. QualType ArgType = Arg->getType();
  4445. if (!ParamType->isPointerType() ||
  4446. ParamType.getQualifiers().hasAddressSpace() ||
  4447. !ArgType->isPointerType() ||
  4448. !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
  4449. OverloadParams.push_back(ParamType);
  4450. continue;
  4451. }
  4452. NeedsNewDecl = true;
  4453. LangAS AS = ArgType->getPointeeType().getAddressSpace();
  4454. QualType PointeeType = ParamType->getPointeeType();
  4455. PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
  4456. OverloadParams.push_back(Context.getPointerType(PointeeType));
  4457. }
  4458. if (!NeedsNewDecl)
  4459. return nullptr;
  4460. FunctionProtoType::ExtProtoInfo EPI;
  4461. QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
  4462. OverloadParams, EPI);
  4463. DeclContext *Parent = Context.getTranslationUnitDecl();
  4464. FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
  4465. FDecl->getLocation(),
  4466. FDecl->getLocation(),
  4467. FDecl->getIdentifier(),
  4468. OverloadTy,
  4469. /*TInfo=*/nullptr,
  4470. SC_Extern, false,
  4471. /*hasPrototype=*/true);
  4472. SmallVector<ParmVarDecl*, 16> Params;
  4473. FT = cast<FunctionProtoType>(OverloadTy);
  4474. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  4475. QualType ParamType = FT->getParamType(i);
  4476. ParmVarDecl *Parm =
  4477. ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
  4478. SourceLocation(), nullptr, ParamType,
  4479. /*TInfo=*/nullptr, SC_None, nullptr);
  4480. Parm->setScopeInfo(0, i);
  4481. Params.push_back(Parm);
  4482. }
  4483. OverloadDecl->setParams(Params);
  4484. return OverloadDecl;
  4485. }
  4486. static void checkDirectCallValidity(Sema &S, const Expr *Fn,
  4487. FunctionDecl *Callee,
  4488. MultiExprArg ArgExprs) {
  4489. // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
  4490. // similar attributes) really don't like it when functions are called with an
  4491. // invalid number of args.
  4492. if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
  4493. /*PartialOverloading=*/false) &&
  4494. !Callee->isVariadic())
  4495. return;
  4496. if (Callee->getMinRequiredArguments() > ArgExprs.size())
  4497. return;
  4498. if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
  4499. S.Diag(Fn->getLocStart(),
  4500. isa<CXXMethodDecl>(Callee)
  4501. ? diag::err_ovl_no_viable_member_function_in_call
  4502. : diag::err_ovl_no_viable_function_in_call)
  4503. << Callee << Callee->getSourceRange();
  4504. S.Diag(Callee->getLocation(),
  4505. diag::note_ovl_candidate_disabled_by_function_cond_attr)
  4506. << Attr->getCond()->getSourceRange() << Attr->getMessage();
  4507. return;
  4508. }
  4509. }
  4510. static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
  4511. const UnresolvedMemberExpr *const UME, Sema &S) {
  4512. const auto GetFunctionLevelDCIfCXXClass =
  4513. [](Sema &S) -> const CXXRecordDecl * {
  4514. const DeclContext *const DC = S.getFunctionLevelDeclContext();
  4515. if (!DC || !DC->getParent())
  4516. return nullptr;
  4517. // If the call to some member function was made from within a member
  4518. // function body 'M' return return 'M's parent.
  4519. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  4520. return MD->getParent()->getCanonicalDecl();
  4521. // else the call was made from within a default member initializer of a
  4522. // class, so return the class.
  4523. if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
  4524. return RD->getCanonicalDecl();
  4525. return nullptr;
  4526. };
  4527. // If our DeclContext is neither a member function nor a class (in the
  4528. // case of a lambda in a default member initializer), we can't have an
  4529. // enclosing 'this'.
  4530. const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
  4531. if (!CurParentClass)
  4532. return false;
  4533. // The naming class for implicit member functions call is the class in which
  4534. // name lookup starts.
  4535. const CXXRecordDecl *const NamingClass =
  4536. UME->getNamingClass()->getCanonicalDecl();
  4537. assert(NamingClass && "Must have naming class even for implicit access");
  4538. // If the unresolved member functions were found in a 'naming class' that is
  4539. // related (either the same or derived from) to the class that contains the
  4540. // member function that itself contained the implicit member access.
  4541. return CurParentClass == NamingClass ||
  4542. CurParentClass->isDerivedFrom(NamingClass);
  4543. }
  4544. static void
  4545. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4546. Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
  4547. if (!UME)
  4548. return;
  4549. LambdaScopeInfo *const CurLSI = S.getCurLambda();
  4550. // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
  4551. // already been captured, or if this is an implicit member function call (if
  4552. // it isn't, an attempt to capture 'this' should already have been made).
  4553. if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
  4554. !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
  4555. return;
  4556. // Check if the naming class in which the unresolved members were found is
  4557. // related (same as or is a base of) to the enclosing class.
  4558. if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
  4559. return;
  4560. DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
  4561. // If the enclosing function is not dependent, then this lambda is
  4562. // capture ready, so if we can capture this, do so.
  4563. if (!EnclosingFunctionCtx->isDependentContext()) {
  4564. // If the current lambda and all enclosing lambdas can capture 'this' -
  4565. // then go ahead and capture 'this' (since our unresolved overload set
  4566. // contains at least one non-static member function).
  4567. if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
  4568. S.CheckCXXThisCapture(CallLoc);
  4569. } else if (S.CurContext->isDependentContext()) {
  4570. // ... since this is an implicit member reference, that might potentially
  4571. // involve a 'this' capture, mark 'this' for potential capture in
  4572. // enclosing lambdas.
  4573. if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
  4574. CurLSI->addPotentialThisCapture(CallLoc);
  4575. }
  4576. }
  4577. /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
  4578. /// This provides the location of the left/right parens and a list of comma
  4579. /// locations.
  4580. ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
  4581. MultiExprArg ArgExprs, SourceLocation RParenLoc,
  4582. Expr *ExecConfig, bool IsExecConfig) {
  4583. // Since this might be a postfix expression, get rid of ParenListExprs.
  4584. ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
  4585. if (Result.isInvalid()) return ExprError();
  4586. Fn = Result.get();
  4587. if (checkArgsForPlaceholders(*this, ArgExprs))
  4588. return ExprError();
  4589. if (getLangOpts().CPlusPlus) {
  4590. // If this is a pseudo-destructor expression, build the call immediately.
  4591. if (isa<CXXPseudoDestructorExpr>(Fn)) {
  4592. if (!ArgExprs.empty()) {
  4593. // Pseudo-destructor calls should not have any arguments.
  4594. Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
  4595. << FixItHint::CreateRemoval(
  4596. SourceRange(ArgExprs.front()->getLocStart(),
  4597. ArgExprs.back()->getLocEnd()));
  4598. }
  4599. return new (Context)
  4600. CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
  4601. }
  4602. if (Fn->getType() == Context.PseudoObjectTy) {
  4603. ExprResult result = CheckPlaceholderExpr(Fn);
  4604. if (result.isInvalid()) return ExprError();
  4605. Fn = result.get();
  4606. }
  4607. // Determine whether this is a dependent call inside a C++ template,
  4608. // in which case we won't do any semantic analysis now.
  4609. bool Dependent = false;
  4610. if (Fn->isTypeDependent())
  4611. Dependent = true;
  4612. else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4613. Dependent = true;
  4614. if (Dependent) {
  4615. if (ExecConfig) {
  4616. return new (Context) CUDAKernelCallExpr(
  4617. Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
  4618. Context.DependentTy, VK_RValue, RParenLoc);
  4619. } else {
  4620. tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
  4621. *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
  4622. Fn->getLocStart());
  4623. return new (Context) CallExpr(
  4624. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4625. }
  4626. }
  4627. // Determine whether this is a call to an object (C++ [over.call.object]).
  4628. if (Fn->getType()->isRecordType())
  4629. return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
  4630. RParenLoc);
  4631. if (Fn->getType() == Context.UnknownAnyTy) {
  4632. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4633. if (result.isInvalid()) return ExprError();
  4634. Fn = result.get();
  4635. }
  4636. if (Fn->getType() == Context.BoundMemberTy) {
  4637. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4638. RParenLoc);
  4639. }
  4640. }
  4641. // Check for overloaded calls. This can happen even in C due to extensions.
  4642. if (Fn->getType() == Context.OverloadTy) {
  4643. OverloadExpr::FindResult find = OverloadExpr::find(Fn);
  4644. // We aren't supposed to apply this logic if there's an '&' involved.
  4645. if (!find.HasFormOfMemberPointer) {
  4646. if (Expr::hasAnyTypeDependentArguments(ArgExprs))
  4647. return new (Context) CallExpr(
  4648. Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
  4649. OverloadExpr *ovl = find.Expression;
  4650. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
  4651. return BuildOverloadedCallExpr(
  4652. Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
  4653. /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
  4654. return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
  4655. RParenLoc);
  4656. }
  4657. }
  4658. // If we're directly calling a function, get the appropriate declaration.
  4659. if (Fn->getType() == Context.UnknownAnyTy) {
  4660. ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
  4661. if (result.isInvalid()) return ExprError();
  4662. Fn = result.get();
  4663. }
  4664. Expr *NakedFn = Fn->IgnoreParens();
  4665. bool CallingNDeclIndirectly = false;
  4666. NamedDecl *NDecl = nullptr;
  4667. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
  4668. if (UnOp->getOpcode() == UO_AddrOf) {
  4669. CallingNDeclIndirectly = true;
  4670. NakedFn = UnOp->getSubExpr()->IgnoreParens();
  4671. }
  4672. }
  4673. if (isa<DeclRefExpr>(NakedFn)) {
  4674. NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
  4675. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
  4676. if (FDecl && FDecl->getBuiltinID()) {
  4677. // Rewrite the function decl for this builtin by replacing parameters
  4678. // with no explicit address space with the address space of the arguments
  4679. // in ArgExprs.
  4680. if ((FDecl =
  4681. rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
  4682. NDecl = FDecl;
  4683. Fn = DeclRefExpr::Create(
  4684. Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
  4685. SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
  4686. }
  4687. }
  4688. } else if (isa<MemberExpr>(NakedFn))
  4689. NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
  4690. if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
  4691. if (CallingNDeclIndirectly &&
  4692. !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  4693. Fn->getLocStart()))
  4694. return ExprError();
  4695. if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
  4696. return ExprError();
  4697. checkDirectCallValidity(*this, Fn, FD, ArgExprs);
  4698. }
  4699. return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
  4700. ExecConfig, IsExecConfig);
  4701. }
  4702. /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
  4703. ///
  4704. /// __builtin_astype( value, dst type )
  4705. ///
  4706. ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
  4707. SourceLocation BuiltinLoc,
  4708. SourceLocation RParenLoc) {
  4709. ExprValueKind VK = VK_RValue;
  4710. ExprObjectKind OK = OK_Ordinary;
  4711. QualType DstTy = GetTypeFromParser(ParsedDestTy);
  4712. QualType SrcTy = E->getType();
  4713. if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
  4714. return ExprError(Diag(BuiltinLoc,
  4715. diag::err_invalid_astype_of_different_size)
  4716. << DstTy
  4717. << SrcTy
  4718. << E->getSourceRange());
  4719. return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  4720. }
  4721. /// ActOnConvertVectorExpr - create a new convert-vector expression from the
  4722. /// provided arguments.
  4723. ///
  4724. /// __builtin_convertvector( value, dst type )
  4725. ///
  4726. ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
  4727. SourceLocation BuiltinLoc,
  4728. SourceLocation RParenLoc) {
  4729. TypeSourceInfo *TInfo;
  4730. GetTypeFromParser(ParsedDestTy, &TInfo);
  4731. return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
  4732. }
  4733. /// BuildResolvedCallExpr - Build a call to a resolved expression,
  4734. /// i.e. an expression not of \p OverloadTy. The expression should
  4735. /// unary-convert to an expression of function-pointer or
  4736. /// block-pointer type.
  4737. ///
  4738. /// \param NDecl the declaration being called, if available
  4739. ExprResult
  4740. Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
  4741. SourceLocation LParenLoc,
  4742. ArrayRef<Expr *> Args,
  4743. SourceLocation RParenLoc,
  4744. Expr *Config, bool IsExecConfig) {
  4745. FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
  4746. unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
  4747. // Functions with 'interrupt' attribute cannot be called directly.
  4748. if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
  4749. Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
  4750. return ExprError();
  4751. }
  4752. // Interrupt handlers don't save off the VFP regs automatically on ARM,
  4753. // so there's some risk when calling out to non-interrupt handler functions
  4754. // that the callee might not preserve them. This is easy to diagnose here,
  4755. // but can be very challenging to debug.
  4756. if (auto *Caller = getCurFunctionDecl())
  4757. if (Caller->hasAttr<ARMInterruptAttr>()) {
  4758. bool VFP = Context.getTargetInfo().hasFeature("vfp");
  4759. if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
  4760. Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
  4761. }
  4762. // Promote the function operand.
  4763. // We special-case function promotion here because we only allow promoting
  4764. // builtin functions to function pointers in the callee of a call.
  4765. ExprResult Result;
  4766. if (BuiltinID &&
  4767. Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
  4768. Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
  4769. CK_BuiltinFnToFnPtr).get();
  4770. } else {
  4771. Result = CallExprUnaryConversions(Fn);
  4772. }
  4773. if (Result.isInvalid())
  4774. return ExprError();
  4775. Fn = Result.get();
  4776. // Make the call expr early, before semantic checks. This guarantees cleanup
  4777. // of arguments and function on error.
  4778. CallExpr *TheCall;
  4779. if (Config)
  4780. TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
  4781. cast<CallExpr>(Config), Args,
  4782. Context.BoolTy, VK_RValue,
  4783. RParenLoc);
  4784. else
  4785. TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
  4786. VK_RValue, RParenLoc);
  4787. if (!getLangOpts().CPlusPlus) {
  4788. // C cannot always handle TypoExpr nodes in builtin calls and direct
  4789. // function calls as their argument checking don't necessarily handle
  4790. // dependent types properly, so make sure any TypoExprs have been
  4791. // dealt with.
  4792. ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
  4793. if (!Result.isUsable()) return ExprError();
  4794. TheCall = dyn_cast<CallExpr>(Result.get());
  4795. if (!TheCall) return Result;
  4796. Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
  4797. }
  4798. // Bail out early if calling a builtin with custom typechecking.
  4799. if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
  4800. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4801. retry:
  4802. const FunctionType *FuncT;
  4803. if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
  4804. // C99 6.5.2.2p1 - "The expression that denotes the called function shall
  4805. // have type pointer to function".
  4806. FuncT = PT->getPointeeType()->getAs<FunctionType>();
  4807. if (!FuncT)
  4808. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4809. << Fn->getType() << Fn->getSourceRange());
  4810. } else if (const BlockPointerType *BPT =
  4811. Fn->getType()->getAs<BlockPointerType>()) {
  4812. FuncT = BPT->getPointeeType()->castAs<FunctionType>();
  4813. } else {
  4814. // Handle calls to expressions of unknown-any type.
  4815. if (Fn->getType() == Context.UnknownAnyTy) {
  4816. ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
  4817. if (rewrite.isInvalid()) return ExprError();
  4818. Fn = rewrite.get();
  4819. TheCall->setCallee(Fn);
  4820. goto retry;
  4821. }
  4822. return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
  4823. << Fn->getType() << Fn->getSourceRange());
  4824. }
  4825. if (getLangOpts().CUDA) {
  4826. if (Config) {
  4827. // CUDA: Kernel calls must be to global functions
  4828. if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
  4829. return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
  4830. << FDecl->getName() << Fn->getSourceRange());
  4831. // CUDA: Kernel function must have 'void' return type
  4832. if (!FuncT->getReturnType()->isVoidType())
  4833. return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
  4834. << Fn->getType() << Fn->getSourceRange());
  4835. } else {
  4836. // CUDA: Calls to global functions must be configured
  4837. if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
  4838. return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
  4839. << FDecl->getName() << Fn->getSourceRange());
  4840. }
  4841. }
  4842. // Check for a valid return type
  4843. if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
  4844. FDecl))
  4845. return ExprError();
  4846. // We know the result type of the call, set it.
  4847. TheCall->setType(FuncT->getCallResultType(Context));
  4848. TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
  4849. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
  4850. if (Proto) {
  4851. if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
  4852. IsExecConfig))
  4853. return ExprError();
  4854. } else {
  4855. assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
  4856. if (FDecl) {
  4857. // Check if we have too few/too many template arguments, based
  4858. // on our knowledge of the function definition.
  4859. const FunctionDecl *Def = nullptr;
  4860. if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
  4861. Proto = Def->getType()->getAs<FunctionProtoType>();
  4862. if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
  4863. Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
  4864. << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
  4865. }
  4866. // If the function we're calling isn't a function prototype, but we have
  4867. // a function prototype from a prior declaratiom, use that prototype.
  4868. if (!FDecl->hasPrototype())
  4869. Proto = FDecl->getType()->getAs<FunctionProtoType>();
  4870. }
  4871. // Promote the arguments (C99 6.5.2.2p6).
  4872. for (unsigned i = 0, e = Args.size(); i != e; i++) {
  4873. Expr *Arg = Args[i];
  4874. if (Proto && i < Proto->getNumParams()) {
  4875. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  4876. Context, Proto->getParamType(i), Proto->isParamConsumed(i));
  4877. ExprResult ArgE =
  4878. PerformCopyInitialization(Entity, SourceLocation(), Arg);
  4879. if (ArgE.isInvalid())
  4880. return true;
  4881. Arg = ArgE.getAs<Expr>();
  4882. } else {
  4883. ExprResult ArgE = DefaultArgumentPromotion(Arg);
  4884. if (ArgE.isInvalid())
  4885. return true;
  4886. Arg = ArgE.getAs<Expr>();
  4887. }
  4888. if (RequireCompleteType(Arg->getLocStart(),
  4889. Arg->getType(),
  4890. diag::err_call_incomplete_argument, Arg))
  4891. return ExprError();
  4892. TheCall->setArg(i, Arg);
  4893. }
  4894. }
  4895. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
  4896. if (!Method->isStatic())
  4897. return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
  4898. << Fn->getSourceRange());
  4899. // Check for sentinels
  4900. if (NDecl)
  4901. DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
  4902. // Do special checking on direct calls to functions.
  4903. if (FDecl) {
  4904. if (CheckFunctionCall(FDecl, TheCall, Proto))
  4905. return ExprError();
  4906. if (BuiltinID)
  4907. return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
  4908. } else if (NDecl) {
  4909. if (CheckPointerCall(NDecl, TheCall, Proto))
  4910. return ExprError();
  4911. } else {
  4912. if (CheckOtherCall(TheCall, Proto))
  4913. return ExprError();
  4914. }
  4915. return MaybeBindToTemporary(TheCall);
  4916. }
  4917. ExprResult
  4918. Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
  4919. SourceLocation RParenLoc, Expr *InitExpr) {
  4920. assert(Ty && "ActOnCompoundLiteral(): missing type");
  4921. assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
  4922. TypeSourceInfo *TInfo;
  4923. QualType literalType = GetTypeFromParser(Ty, &TInfo);
  4924. if (!TInfo)
  4925. TInfo = Context.getTrivialTypeSourceInfo(literalType);
  4926. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
  4927. }
  4928. ExprResult
  4929. Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
  4930. SourceLocation RParenLoc, Expr *LiteralExpr) {
  4931. QualType literalType = TInfo->getType();
  4932. if (literalType->isArrayType()) {
  4933. if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
  4934. diag::err_illegal_decl_array_incomplete_type,
  4935. SourceRange(LParenLoc,
  4936. LiteralExpr->getSourceRange().getEnd())))
  4937. return ExprError();
  4938. if (literalType->isVariableArrayType())
  4939. return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
  4940. << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
  4941. } else if (!literalType->isDependentType() &&
  4942. RequireCompleteType(LParenLoc, literalType,
  4943. diag::err_typecheck_decl_incomplete_type,
  4944. SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
  4945. return ExprError();
  4946. InitializedEntity Entity
  4947. = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
  4948. InitializationKind Kind
  4949. = InitializationKind::CreateCStyleCast(LParenLoc,
  4950. SourceRange(LParenLoc, RParenLoc),
  4951. /*InitList=*/true);
  4952. InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
  4953. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
  4954. &literalType);
  4955. if (Result.isInvalid())
  4956. return ExprError();
  4957. LiteralExpr = Result.get();
  4958. bool isFileScope = !CurContext->isFunctionOrMethod();
  4959. if (isFileScope &&
  4960. !LiteralExpr->isTypeDependent() &&
  4961. !LiteralExpr->isValueDependent() &&
  4962. !literalType->isDependentType()) { // 6.5.2.5p3
  4963. if (CheckForConstantInitializer(LiteralExpr, literalType))
  4964. return ExprError();
  4965. }
  4966. // In C, compound literals are l-values for some reason.
  4967. // For GCC compatibility, in C++, file-scope array compound literals with
  4968. // constant initializers are also l-values, and compound literals are
  4969. // otherwise prvalues.
  4970. //
  4971. // (GCC also treats C++ list-initialized file-scope array prvalues with
  4972. // constant initializers as l-values, but that's non-conforming, so we don't
  4973. // follow it there.)
  4974. //
  4975. // FIXME: It would be better to handle the lvalue cases as materializing and
  4976. // lifetime-extending a temporary object, but our materialized temporaries
  4977. // representation only supports lifetime extension from a variable, not "out
  4978. // of thin air".
  4979. // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
  4980. // is bound to the result of applying array-to-pointer decay to the compound
  4981. // literal.
  4982. // FIXME: GCC supports compound literals of reference type, which should
  4983. // obviously have a value kind derived from the kind of reference involved.
  4984. ExprValueKind VK =
  4985. (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
  4986. ? VK_RValue
  4987. : VK_LValue;
  4988. return MaybeBindToTemporary(
  4989. new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
  4990. VK, LiteralExpr, isFileScope));
  4991. }
  4992. ExprResult
  4993. Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
  4994. SourceLocation RBraceLoc) {
  4995. // Immediately handle non-overload placeholders. Overloads can be
  4996. // resolved contextually, but everything else here can't.
  4997. for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
  4998. if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
  4999. ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
  5000. // Ignore failures; dropping the entire initializer list because
  5001. // of one failure would be terrible for indexing/etc.
  5002. if (result.isInvalid()) continue;
  5003. InitArgList[I] = result.get();
  5004. }
  5005. }
  5006. // Semantic analysis for initializers is done by ActOnDeclarator() and
  5007. // CheckInitializer() - it requires knowledge of the object being intialized.
  5008. InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
  5009. RBraceLoc);
  5010. E->setType(Context.VoidTy); // FIXME: just a place holder for now.
  5011. return E;
  5012. }
  5013. /// Do an explicit extend of the given block pointer if we're in ARC.
  5014. void Sema::maybeExtendBlockObject(ExprResult &E) {
  5015. assert(E.get()->getType()->isBlockPointerType());
  5016. assert(E.get()->isRValue());
  5017. // Only do this in an r-value context.
  5018. if (!getLangOpts().ObjCAutoRefCount) return;
  5019. E = ImplicitCastExpr::Create(Context, E.get()->getType(),
  5020. CK_ARCExtendBlockObject, E.get(),
  5021. /*base path*/ nullptr, VK_RValue);
  5022. Cleanup.setExprNeedsCleanups(true);
  5023. }
  5024. /// Prepare a conversion of the given expression to an ObjC object
  5025. /// pointer type.
  5026. CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
  5027. QualType type = E.get()->getType();
  5028. if (type->isObjCObjectPointerType()) {
  5029. return CK_BitCast;
  5030. } else if (type->isBlockPointerType()) {
  5031. maybeExtendBlockObject(E);
  5032. return CK_BlockPointerToObjCPointerCast;
  5033. } else {
  5034. assert(type->isPointerType());
  5035. return CK_CPointerToObjCPointerCast;
  5036. }
  5037. }
  5038. /// Prepares for a scalar cast, performing all the necessary stages
  5039. /// except the final cast and returning the kind required.
  5040. CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
  5041. // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
  5042. // Also, callers should have filtered out the invalid cases with
  5043. // pointers. Everything else should be possible.
  5044. QualType SrcTy = Src.get()->getType();
  5045. if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
  5046. return CK_NoOp;
  5047. switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
  5048. case Type::STK_MemberPointer:
  5049. llvm_unreachable("member pointer type in C");
  5050. case Type::STK_CPointer:
  5051. case Type::STK_BlockPointer:
  5052. case Type::STK_ObjCObjectPointer:
  5053. switch (DestTy->getScalarTypeKind()) {
  5054. case Type::STK_CPointer: {
  5055. LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
  5056. LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
  5057. if (SrcAS != DestAS)
  5058. return CK_AddressSpaceConversion;
  5059. return CK_BitCast;
  5060. }
  5061. case Type::STK_BlockPointer:
  5062. return (SrcKind == Type::STK_BlockPointer
  5063. ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
  5064. case Type::STK_ObjCObjectPointer:
  5065. if (SrcKind == Type::STK_ObjCObjectPointer)
  5066. return CK_BitCast;
  5067. if (SrcKind == Type::STK_CPointer)
  5068. return CK_CPointerToObjCPointerCast;
  5069. maybeExtendBlockObject(Src);
  5070. return CK_BlockPointerToObjCPointerCast;
  5071. case Type::STK_Bool:
  5072. return CK_PointerToBoolean;
  5073. case Type::STK_Integral:
  5074. return CK_PointerToIntegral;
  5075. case Type::STK_Floating:
  5076. case Type::STK_FloatingComplex:
  5077. case Type::STK_IntegralComplex:
  5078. case Type::STK_MemberPointer:
  5079. llvm_unreachable("illegal cast from pointer");
  5080. }
  5081. llvm_unreachable("Should have returned before this");
  5082. case Type::STK_Bool: // casting from bool is like casting from an integer
  5083. case Type::STK_Integral:
  5084. switch (DestTy->getScalarTypeKind()) {
  5085. case Type::STK_CPointer:
  5086. case Type::STK_ObjCObjectPointer:
  5087. case Type::STK_BlockPointer:
  5088. if (Src.get()->isNullPointerConstant(Context,
  5089. Expr::NPC_ValueDependentIsNull))
  5090. return CK_NullToPointer;
  5091. return CK_IntegralToPointer;
  5092. case Type::STK_Bool:
  5093. return CK_IntegralToBoolean;
  5094. case Type::STK_Integral:
  5095. return CK_IntegralCast;
  5096. case Type::STK_Floating:
  5097. return CK_IntegralToFloating;
  5098. case Type::STK_IntegralComplex:
  5099. Src = ImpCastExprToType(Src.get(),
  5100. DestTy->castAs<ComplexType>()->getElementType(),
  5101. CK_IntegralCast);
  5102. return CK_IntegralRealToComplex;
  5103. case Type::STK_FloatingComplex:
  5104. Src = ImpCastExprToType(Src.get(),
  5105. DestTy->castAs<ComplexType>()->getElementType(),
  5106. CK_IntegralToFloating);
  5107. return CK_FloatingRealToComplex;
  5108. case Type::STK_MemberPointer:
  5109. llvm_unreachable("member pointer type in C");
  5110. }
  5111. llvm_unreachable("Should have returned before this");
  5112. case Type::STK_Floating:
  5113. switch (DestTy->getScalarTypeKind()) {
  5114. case Type::STK_Floating:
  5115. return CK_FloatingCast;
  5116. case Type::STK_Bool:
  5117. return CK_FloatingToBoolean;
  5118. case Type::STK_Integral:
  5119. return CK_FloatingToIntegral;
  5120. case Type::STK_FloatingComplex:
  5121. Src = ImpCastExprToType(Src.get(),
  5122. DestTy->castAs<ComplexType>()->getElementType(),
  5123. CK_FloatingCast);
  5124. return CK_FloatingRealToComplex;
  5125. case Type::STK_IntegralComplex:
  5126. Src = ImpCastExprToType(Src.get(),
  5127. DestTy->castAs<ComplexType>()->getElementType(),
  5128. CK_FloatingToIntegral);
  5129. return CK_IntegralRealToComplex;
  5130. case Type::STK_CPointer:
  5131. case Type::STK_ObjCObjectPointer:
  5132. case Type::STK_BlockPointer:
  5133. llvm_unreachable("valid float->pointer cast?");
  5134. case Type::STK_MemberPointer:
  5135. llvm_unreachable("member pointer type in C");
  5136. }
  5137. llvm_unreachable("Should have returned before this");
  5138. case Type::STK_FloatingComplex:
  5139. switch (DestTy->getScalarTypeKind()) {
  5140. case Type::STK_FloatingComplex:
  5141. return CK_FloatingComplexCast;
  5142. case Type::STK_IntegralComplex:
  5143. return CK_FloatingComplexToIntegralComplex;
  5144. case Type::STK_Floating: {
  5145. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5146. if (Context.hasSameType(ET, DestTy))
  5147. return CK_FloatingComplexToReal;
  5148. Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
  5149. return CK_FloatingCast;
  5150. }
  5151. case Type::STK_Bool:
  5152. return CK_FloatingComplexToBoolean;
  5153. case Type::STK_Integral:
  5154. Src = ImpCastExprToType(Src.get(),
  5155. SrcTy->castAs<ComplexType>()->getElementType(),
  5156. CK_FloatingComplexToReal);
  5157. return CK_FloatingToIntegral;
  5158. case Type::STK_CPointer:
  5159. case Type::STK_ObjCObjectPointer:
  5160. case Type::STK_BlockPointer:
  5161. llvm_unreachable("valid complex float->pointer cast?");
  5162. case Type::STK_MemberPointer:
  5163. llvm_unreachable("member pointer type in C");
  5164. }
  5165. llvm_unreachable("Should have returned before this");
  5166. case Type::STK_IntegralComplex:
  5167. switch (DestTy->getScalarTypeKind()) {
  5168. case Type::STK_FloatingComplex:
  5169. return CK_IntegralComplexToFloatingComplex;
  5170. case Type::STK_IntegralComplex:
  5171. return CK_IntegralComplexCast;
  5172. case Type::STK_Integral: {
  5173. QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
  5174. if (Context.hasSameType(ET, DestTy))
  5175. return CK_IntegralComplexToReal;
  5176. Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
  5177. return CK_IntegralCast;
  5178. }
  5179. case Type::STK_Bool:
  5180. return CK_IntegralComplexToBoolean;
  5181. case Type::STK_Floating:
  5182. Src = ImpCastExprToType(Src.get(),
  5183. SrcTy->castAs<ComplexType>()->getElementType(),
  5184. CK_IntegralComplexToReal);
  5185. return CK_IntegralToFloating;
  5186. case Type::STK_CPointer:
  5187. case Type::STK_ObjCObjectPointer:
  5188. case Type::STK_BlockPointer:
  5189. llvm_unreachable("valid complex int->pointer cast?");
  5190. case Type::STK_MemberPointer:
  5191. llvm_unreachable("member pointer type in C");
  5192. }
  5193. llvm_unreachable("Should have returned before this");
  5194. }
  5195. llvm_unreachable("Unhandled scalar cast");
  5196. }
  5197. static bool breakDownVectorType(QualType type, uint64_t &len,
  5198. QualType &eltType) {
  5199. // Vectors are simple.
  5200. if (const VectorType *vecType = type->getAs<VectorType>()) {
  5201. len = vecType->getNumElements();
  5202. eltType = vecType->getElementType();
  5203. assert(eltType->isScalarType());
  5204. return true;
  5205. }
  5206. // We allow lax conversion to and from non-vector types, but only if
  5207. // they're real types (i.e. non-complex, non-pointer scalar types).
  5208. if (!type->isRealType()) return false;
  5209. len = 1;
  5210. eltType = type;
  5211. return true;
  5212. }
  5213. /// Are the two types lax-compatible vector types? That is, given
  5214. /// that one of them is a vector, do they have equal storage sizes,
  5215. /// where the storage size is the number of elements times the element
  5216. /// size?
  5217. ///
  5218. /// This will also return false if either of the types is neither a
  5219. /// vector nor a real type.
  5220. bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
  5221. assert(destTy->isVectorType() || srcTy->isVectorType());
  5222. // Disallow lax conversions between scalars and ExtVectors (these
  5223. // conversions are allowed for other vector types because common headers
  5224. // depend on them). Most scalar OP ExtVector cases are handled by the
  5225. // splat path anyway, which does what we want (convert, not bitcast).
  5226. // What this rules out for ExtVectors is crazy things like char4*float.
  5227. if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
  5228. if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
  5229. uint64_t srcLen, destLen;
  5230. QualType srcEltTy, destEltTy;
  5231. if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
  5232. if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
  5233. // ASTContext::getTypeSize will return the size rounded up to a
  5234. // power of 2, so instead of using that, we need to use the raw
  5235. // element size multiplied by the element count.
  5236. uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
  5237. uint64_t destEltSize = Context.getTypeSize(destEltTy);
  5238. return (srcLen * srcEltSize == destLen * destEltSize);
  5239. }
  5240. /// Is this a legal conversion between two types, one of which is
  5241. /// known to be a vector type?
  5242. bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
  5243. assert(destTy->isVectorType() || srcTy->isVectorType());
  5244. if (!Context.getLangOpts().LaxVectorConversions)
  5245. return false;
  5246. return areLaxCompatibleVectorTypes(srcTy, destTy);
  5247. }
  5248. bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
  5249. CastKind &Kind) {
  5250. assert(VectorTy->isVectorType() && "Not a vector type!");
  5251. if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
  5252. if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
  5253. return Diag(R.getBegin(),
  5254. Ty->isVectorType() ?
  5255. diag::err_invalid_conversion_between_vectors :
  5256. diag::err_invalid_conversion_between_vector_and_integer)
  5257. << VectorTy << Ty << R;
  5258. } else
  5259. return Diag(R.getBegin(),
  5260. diag::err_invalid_conversion_between_vector_and_scalar)
  5261. << VectorTy << Ty << R;
  5262. Kind = CK_BitCast;
  5263. return false;
  5264. }
  5265. ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
  5266. QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
  5267. if (DestElemTy == SplattedExpr->getType())
  5268. return SplattedExpr;
  5269. assert(DestElemTy->isFloatingType() ||
  5270. DestElemTy->isIntegralOrEnumerationType());
  5271. CastKind CK;
  5272. if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
  5273. // OpenCL requires that we convert `true` boolean expressions to -1, but
  5274. // only when splatting vectors.
  5275. if (DestElemTy->isFloatingType()) {
  5276. // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
  5277. // in two steps: boolean to signed integral, then to floating.
  5278. ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
  5279. CK_BooleanToSignedIntegral);
  5280. SplattedExpr = CastExprRes.get();
  5281. CK = CK_IntegralToFloating;
  5282. } else {
  5283. CK = CK_BooleanToSignedIntegral;
  5284. }
  5285. } else {
  5286. ExprResult CastExprRes = SplattedExpr;
  5287. CK = PrepareScalarCast(CastExprRes, DestElemTy);
  5288. if (CastExprRes.isInvalid())
  5289. return ExprError();
  5290. SplattedExpr = CastExprRes.get();
  5291. }
  5292. return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
  5293. }
  5294. ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
  5295. Expr *CastExpr, CastKind &Kind) {
  5296. assert(DestTy->isExtVectorType() && "Not an extended vector type!");
  5297. QualType SrcTy = CastExpr->getType();
  5298. // If SrcTy is a VectorType, the total size must match to explicitly cast to
  5299. // an ExtVectorType.
  5300. // In OpenCL, casts between vectors of different types are not allowed.
  5301. // (See OpenCL 6.2).
  5302. if (SrcTy->isVectorType()) {
  5303. if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
  5304. (getLangOpts().OpenCL &&
  5305. !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
  5306. Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
  5307. << DestTy << SrcTy << R;
  5308. return ExprError();
  5309. }
  5310. Kind = CK_BitCast;
  5311. return CastExpr;
  5312. }
  5313. // All non-pointer scalars can be cast to ExtVector type. The appropriate
  5314. // conversion will take place first from scalar to elt type, and then
  5315. // splat from elt type to vector.
  5316. if (SrcTy->isPointerType())
  5317. return Diag(R.getBegin(),
  5318. diag::err_invalid_conversion_between_vector_and_scalar)
  5319. << DestTy << SrcTy << R;
  5320. Kind = CK_VectorSplat;
  5321. return prepareVectorSplat(DestTy, CastExpr);
  5322. }
  5323. ExprResult
  5324. Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
  5325. Declarator &D, ParsedType &Ty,
  5326. SourceLocation RParenLoc, Expr *CastExpr) {
  5327. assert(!D.isInvalidType() && (CastExpr != nullptr) &&
  5328. "ActOnCastExpr(): missing type or expr");
  5329. TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
  5330. if (D.isInvalidType())
  5331. return ExprError();
  5332. if (getLangOpts().CPlusPlus) {
  5333. // Check that there are no default arguments (C++ only).
  5334. CheckExtraCXXDefaultArguments(D);
  5335. } else {
  5336. // Make sure any TypoExprs have been dealt with.
  5337. ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
  5338. if (!Res.isUsable())
  5339. return ExprError();
  5340. CastExpr = Res.get();
  5341. }
  5342. checkUnusedDeclAttributes(D);
  5343. QualType castType = castTInfo->getType();
  5344. Ty = CreateParsedType(castType, castTInfo);
  5345. bool isVectorLiteral = false;
  5346. // Check for an altivec or OpenCL literal,
  5347. // i.e. all the elements are integer constants.
  5348. ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
  5349. ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
  5350. if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
  5351. && castType->isVectorType() && (PE || PLE)) {
  5352. if (PLE && PLE->getNumExprs() == 0) {
  5353. Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
  5354. return ExprError();
  5355. }
  5356. if (PE || PLE->getNumExprs() == 1) {
  5357. Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
  5358. if (!E->getType()->isVectorType())
  5359. isVectorLiteral = true;
  5360. }
  5361. else
  5362. isVectorLiteral = true;
  5363. }
  5364. // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
  5365. // then handle it as such.
  5366. if (isVectorLiteral)
  5367. return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
  5368. // If the Expr being casted is a ParenListExpr, handle it specially.
  5369. // This is not an AltiVec-style cast, so turn the ParenListExpr into a
  5370. // sequence of BinOp comma operators.
  5371. if (isa<ParenListExpr>(CastExpr)) {
  5372. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
  5373. if (Result.isInvalid()) return ExprError();
  5374. CastExpr = Result.get();
  5375. }
  5376. if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
  5377. !getSourceManager().isInSystemMacro(LParenLoc))
  5378. Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
  5379. CheckTollFreeBridgeCast(castType, CastExpr);
  5380. CheckObjCBridgeRelatedCast(castType, CastExpr);
  5381. DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
  5382. return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
  5383. }
  5384. ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
  5385. SourceLocation RParenLoc, Expr *E,
  5386. TypeSourceInfo *TInfo) {
  5387. assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
  5388. "Expected paren or paren list expression");
  5389. Expr **exprs;
  5390. unsigned numExprs;
  5391. Expr *subExpr;
  5392. SourceLocation LiteralLParenLoc, LiteralRParenLoc;
  5393. if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
  5394. LiteralLParenLoc = PE->getLParenLoc();
  5395. LiteralRParenLoc = PE->getRParenLoc();
  5396. exprs = PE->getExprs();
  5397. numExprs = PE->getNumExprs();
  5398. } else { // isa<ParenExpr> by assertion at function entrance
  5399. LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
  5400. LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
  5401. subExpr = cast<ParenExpr>(E)->getSubExpr();
  5402. exprs = &subExpr;
  5403. numExprs = 1;
  5404. }
  5405. QualType Ty = TInfo->getType();
  5406. assert(Ty->isVectorType() && "Expected vector type");
  5407. SmallVector<Expr *, 8> initExprs;
  5408. const VectorType *VTy = Ty->getAs<VectorType>();
  5409. unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
  5410. // '(...)' form of vector initialization in AltiVec: the number of
  5411. // initializers must be one or must match the size of the vector.
  5412. // If a single value is specified in the initializer then it will be
  5413. // replicated to all the components of the vector
  5414. if (VTy->getVectorKind() == VectorType::AltiVecVector) {
  5415. // The number of initializers must be one or must match the size of the
  5416. // vector. If a single value is specified in the initializer then it will
  5417. // be replicated to all the components of the vector
  5418. if (numExprs == 1) {
  5419. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5420. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5421. if (Literal.isInvalid())
  5422. return ExprError();
  5423. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5424. PrepareScalarCast(Literal, ElemTy));
  5425. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5426. }
  5427. else if (numExprs < numElems) {
  5428. Diag(E->getExprLoc(),
  5429. diag::err_incorrect_number_of_vector_initializers);
  5430. return ExprError();
  5431. }
  5432. else
  5433. initExprs.append(exprs, exprs + numExprs);
  5434. }
  5435. else {
  5436. // For OpenCL, when the number of initializers is a single value,
  5437. // it will be replicated to all components of the vector.
  5438. if (getLangOpts().OpenCL &&
  5439. VTy->getVectorKind() == VectorType::GenericVector &&
  5440. numExprs == 1) {
  5441. QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
  5442. ExprResult Literal = DefaultLvalueConversion(exprs[0]);
  5443. if (Literal.isInvalid())
  5444. return ExprError();
  5445. Literal = ImpCastExprToType(Literal.get(), ElemTy,
  5446. PrepareScalarCast(Literal, ElemTy));
  5447. return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
  5448. }
  5449. initExprs.append(exprs, exprs + numExprs);
  5450. }
  5451. // FIXME: This means that pretty-printing the final AST will produce curly
  5452. // braces instead of the original commas.
  5453. InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
  5454. initExprs, LiteralRParenLoc);
  5455. initE->setType(Ty);
  5456. return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
  5457. }
  5458. /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
  5459. /// the ParenListExpr into a sequence of comma binary operators.
  5460. ExprResult
  5461. Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
  5462. ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
  5463. if (!E)
  5464. return OrigExpr;
  5465. ExprResult Result(E->getExpr(0));
  5466. for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
  5467. Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
  5468. E->getExpr(i));
  5469. if (Result.isInvalid()) return ExprError();
  5470. return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
  5471. }
  5472. ExprResult Sema::ActOnParenListExpr(SourceLocation L,
  5473. SourceLocation R,
  5474. MultiExprArg Val) {
  5475. Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
  5476. return expr;
  5477. }
  5478. /// \brief Emit a specialized diagnostic when one expression is a null pointer
  5479. /// constant and the other is not a pointer. Returns true if a diagnostic is
  5480. /// emitted.
  5481. bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
  5482. SourceLocation QuestionLoc) {
  5483. Expr *NullExpr = LHSExpr;
  5484. Expr *NonPointerExpr = RHSExpr;
  5485. Expr::NullPointerConstantKind NullKind =
  5486. NullExpr->isNullPointerConstant(Context,
  5487. Expr::NPC_ValueDependentIsNotNull);
  5488. if (NullKind == Expr::NPCK_NotNull) {
  5489. NullExpr = RHSExpr;
  5490. NonPointerExpr = LHSExpr;
  5491. NullKind =
  5492. NullExpr->isNullPointerConstant(Context,
  5493. Expr::NPC_ValueDependentIsNotNull);
  5494. }
  5495. if (NullKind == Expr::NPCK_NotNull)
  5496. return false;
  5497. if (NullKind == Expr::NPCK_ZeroExpression)
  5498. return false;
  5499. if (NullKind == Expr::NPCK_ZeroLiteral) {
  5500. // In this case, check to make sure that we got here from a "NULL"
  5501. // string in the source code.
  5502. NullExpr = NullExpr->IgnoreParenImpCasts();
  5503. SourceLocation loc = NullExpr->getExprLoc();
  5504. if (!findMacroSpelling(loc, "NULL"))
  5505. return false;
  5506. }
  5507. int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
  5508. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
  5509. << NonPointerExpr->getType() << DiagType
  5510. << NonPointerExpr->getSourceRange();
  5511. return true;
  5512. }
  5513. /// \brief Return false if the condition expression is valid, true otherwise.
  5514. static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
  5515. QualType CondTy = Cond->getType();
  5516. // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
  5517. if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
  5518. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5519. << CondTy << Cond->getSourceRange();
  5520. return true;
  5521. }
  5522. // C99 6.5.15p2
  5523. if (CondTy->isScalarType()) return false;
  5524. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
  5525. << CondTy << Cond->getSourceRange();
  5526. return true;
  5527. }
  5528. /// \brief Handle when one or both operands are void type.
  5529. static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
  5530. ExprResult &RHS) {
  5531. Expr *LHSExpr = LHS.get();
  5532. Expr *RHSExpr = RHS.get();
  5533. if (!LHSExpr->getType()->isVoidType())
  5534. S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5535. << RHSExpr->getSourceRange();
  5536. if (!RHSExpr->getType()->isVoidType())
  5537. S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
  5538. << LHSExpr->getSourceRange();
  5539. LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
  5540. RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
  5541. return S.Context.VoidTy;
  5542. }
  5543. /// \brief Return false if the NullExpr can be promoted to PointerTy,
  5544. /// true otherwise.
  5545. static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
  5546. QualType PointerTy) {
  5547. if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
  5548. !NullExpr.get()->isNullPointerConstant(S.Context,
  5549. Expr::NPC_ValueDependentIsNull))
  5550. return true;
  5551. NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
  5552. return false;
  5553. }
  5554. /// \brief Checks compatibility between two pointers and return the resulting
  5555. /// type.
  5556. static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
  5557. ExprResult &RHS,
  5558. SourceLocation Loc) {
  5559. QualType LHSTy = LHS.get()->getType();
  5560. QualType RHSTy = RHS.get()->getType();
  5561. if (S.Context.hasSameType(LHSTy, RHSTy)) {
  5562. // Two identical pointers types are always compatible.
  5563. return LHSTy;
  5564. }
  5565. QualType lhptee, rhptee;
  5566. // Get the pointee types.
  5567. bool IsBlockPointer = false;
  5568. if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
  5569. lhptee = LHSBTy->getPointeeType();
  5570. rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
  5571. IsBlockPointer = true;
  5572. } else {
  5573. lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
  5574. rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
  5575. }
  5576. // C99 6.5.15p6: If both operands are pointers to compatible types or to
  5577. // differently qualified versions of compatible types, the result type is
  5578. // a pointer to an appropriately qualified version of the composite
  5579. // type.
  5580. // Only CVR-qualifiers exist in the standard, and the differently-qualified
  5581. // clause doesn't make sense for our extensions. E.g. address space 2 should
  5582. // be incompatible with address space 3: they may live on different devices or
  5583. // anything.
  5584. Qualifiers lhQual = lhptee.getQualifiers();
  5585. Qualifiers rhQual = rhptee.getQualifiers();
  5586. LangAS ResultAddrSpace = LangAS::Default;
  5587. LangAS LAddrSpace = lhQual.getAddressSpace();
  5588. LangAS RAddrSpace = rhQual.getAddressSpace();
  5589. if (S.getLangOpts().OpenCL) {
  5590. // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
  5591. // spaces is disallowed.
  5592. if (lhQual.isAddressSpaceSupersetOf(rhQual))
  5593. ResultAddrSpace = LAddrSpace;
  5594. else if (rhQual.isAddressSpaceSupersetOf(lhQual))
  5595. ResultAddrSpace = RAddrSpace;
  5596. else {
  5597. S.Diag(Loc,
  5598. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  5599. << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
  5600. << RHS.get()->getSourceRange();
  5601. return QualType();
  5602. }
  5603. }
  5604. unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
  5605. auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
  5606. lhQual.removeCVRQualifiers();
  5607. rhQual.removeCVRQualifiers();
  5608. // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
  5609. // (C99 6.7.3) for address spaces. We assume that the check should behave in
  5610. // the same manner as it's defined for CVR qualifiers, so for OpenCL two
  5611. // qual types are compatible iff
  5612. // * corresponded types are compatible
  5613. // * CVR qualifiers are equal
  5614. // * address spaces are equal
  5615. // Thus for conditional operator we merge CVR and address space unqualified
  5616. // pointees and if there is a composite type we return a pointer to it with
  5617. // merged qualifiers.
  5618. if (S.getLangOpts().OpenCL) {
  5619. LHSCastKind = LAddrSpace == ResultAddrSpace
  5620. ? CK_BitCast
  5621. : CK_AddressSpaceConversion;
  5622. RHSCastKind = RAddrSpace == ResultAddrSpace
  5623. ? CK_BitCast
  5624. : CK_AddressSpaceConversion;
  5625. lhQual.removeAddressSpace();
  5626. rhQual.removeAddressSpace();
  5627. }
  5628. lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
  5629. rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
  5630. QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
  5631. if (CompositeTy.isNull()) {
  5632. // In this situation, we assume void* type. No especially good
  5633. // reason, but this is what gcc does, and we do have to pick
  5634. // to get a consistent AST.
  5635. QualType incompatTy;
  5636. incompatTy = S.Context.getPointerType(
  5637. S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
  5638. LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
  5639. RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
  5640. // FIXME: For OpenCL the warning emission and cast to void* leaves a room
  5641. // for casts between types with incompatible address space qualifiers.
  5642. // For the following code the compiler produces casts between global and
  5643. // local address spaces of the corresponded innermost pointees:
  5644. // local int *global *a;
  5645. // global int *global *b;
  5646. // a = (0 ? a : b); // see C99 6.5.16.1.p1.
  5647. S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
  5648. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5649. << RHS.get()->getSourceRange();
  5650. return incompatTy;
  5651. }
  5652. // The pointer types are compatible.
  5653. // In case of OpenCL ResultTy should have the address space qualifier
  5654. // which is a superset of address spaces of both the 2nd and the 3rd
  5655. // operands of the conditional operator.
  5656. QualType ResultTy = [&, ResultAddrSpace]() {
  5657. if (S.getLangOpts().OpenCL) {
  5658. Qualifiers CompositeQuals = CompositeTy.getQualifiers();
  5659. CompositeQuals.setAddressSpace(ResultAddrSpace);
  5660. return S.Context
  5661. .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
  5662. .withCVRQualifiers(MergedCVRQual);
  5663. }
  5664. return CompositeTy.withCVRQualifiers(MergedCVRQual);
  5665. }();
  5666. if (IsBlockPointer)
  5667. ResultTy = S.Context.getBlockPointerType(ResultTy);
  5668. else
  5669. ResultTy = S.Context.getPointerType(ResultTy);
  5670. LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
  5671. RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
  5672. return ResultTy;
  5673. }
  5674. /// \brief Return the resulting type when the operands are both block pointers.
  5675. static QualType checkConditionalBlockPointerCompatibility(Sema &S,
  5676. ExprResult &LHS,
  5677. ExprResult &RHS,
  5678. SourceLocation Loc) {
  5679. QualType LHSTy = LHS.get()->getType();
  5680. QualType RHSTy = RHS.get()->getType();
  5681. if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
  5682. if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
  5683. QualType destType = S.Context.getPointerType(S.Context.VoidTy);
  5684. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5685. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5686. return destType;
  5687. }
  5688. S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
  5689. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  5690. << RHS.get()->getSourceRange();
  5691. return QualType();
  5692. }
  5693. // We have 2 block pointer types.
  5694. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5695. }
  5696. /// \brief Return the resulting type when the operands are both pointers.
  5697. static QualType
  5698. checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
  5699. ExprResult &RHS,
  5700. SourceLocation Loc) {
  5701. // get the pointer types
  5702. QualType LHSTy = LHS.get()->getType();
  5703. QualType RHSTy = RHS.get()->getType();
  5704. // get the "pointed to" types
  5705. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  5706. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  5707. // ignore qualifiers on void (C99 6.5.15p3, clause 6)
  5708. if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
  5709. // Figure out necessary qualifiers (C99 6.5.15p6)
  5710. QualType destPointee
  5711. = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  5712. QualType destType = S.Context.getPointerType(destPointee);
  5713. // Add qualifiers if necessary.
  5714. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  5715. // Promote to void*.
  5716. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  5717. return destType;
  5718. }
  5719. if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
  5720. QualType destPointee
  5721. = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  5722. QualType destType = S.Context.getPointerType(destPointee);
  5723. // Add qualifiers if necessary.
  5724. RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  5725. // Promote to void*.
  5726. LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  5727. return destType;
  5728. }
  5729. return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
  5730. }
  5731. /// \brief Return false if the first expression is not an integer and the second
  5732. /// expression is not a pointer, true otherwise.
  5733. static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
  5734. Expr* PointerExpr, SourceLocation Loc,
  5735. bool IsIntFirstExpr) {
  5736. if (!PointerExpr->getType()->isPointerType() ||
  5737. !Int.get()->getType()->isIntegerType())
  5738. return false;
  5739. Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
  5740. Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
  5741. S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
  5742. << Expr1->getType() << Expr2->getType()
  5743. << Expr1->getSourceRange() << Expr2->getSourceRange();
  5744. Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
  5745. CK_IntegralToPointer);
  5746. return true;
  5747. }
  5748. /// \brief Simple conversion between integer and floating point types.
  5749. ///
  5750. /// Used when handling the OpenCL conditional operator where the
  5751. /// condition is a vector while the other operands are scalar.
  5752. ///
  5753. /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
  5754. /// types are either integer or floating type. Between the two
  5755. /// operands, the type with the higher rank is defined as the "result
  5756. /// type". The other operand needs to be promoted to the same type. No
  5757. /// other type promotion is allowed. We cannot use
  5758. /// UsualArithmeticConversions() for this purpose, since it always
  5759. /// promotes promotable types.
  5760. static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
  5761. ExprResult &RHS,
  5762. SourceLocation QuestionLoc) {
  5763. LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
  5764. if (LHS.isInvalid())
  5765. return QualType();
  5766. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  5767. if (RHS.isInvalid())
  5768. return QualType();
  5769. // For conversion purposes, we ignore any qualifiers.
  5770. // For example, "const float" and "float" are equivalent.
  5771. QualType LHSType =
  5772. S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
  5773. QualType RHSType =
  5774. S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
  5775. if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
  5776. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5777. << LHSType << LHS.get()->getSourceRange();
  5778. return QualType();
  5779. }
  5780. if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
  5781. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
  5782. << RHSType << RHS.get()->getSourceRange();
  5783. return QualType();
  5784. }
  5785. // If both types are identical, no conversion is needed.
  5786. if (LHSType == RHSType)
  5787. return LHSType;
  5788. // Now handle "real" floating types (i.e. float, double, long double).
  5789. if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
  5790. return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
  5791. /*IsCompAssign = */ false);
  5792. // Finally, we have two differing integer types.
  5793. return handleIntegerConversion<doIntegralCast, doIntegralCast>
  5794. (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
  5795. }
  5796. /// \brief Convert scalar operands to a vector that matches the
  5797. /// condition in length.
  5798. ///
  5799. /// Used when handling the OpenCL conditional operator where the
  5800. /// condition is a vector while the other operands are scalar.
  5801. ///
  5802. /// We first compute the "result type" for the scalar operands
  5803. /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
  5804. /// into a vector of that type where the length matches the condition
  5805. /// vector type. s6.11.6 requires that the element types of the result
  5806. /// and the condition must have the same number of bits.
  5807. static QualType
  5808. OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
  5809. QualType CondTy, SourceLocation QuestionLoc) {
  5810. QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
  5811. if (ResTy.isNull()) return QualType();
  5812. const VectorType *CV = CondTy->getAs<VectorType>();
  5813. assert(CV);
  5814. // Determine the vector result type
  5815. unsigned NumElements = CV->getNumElements();
  5816. QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
  5817. // Ensure that all types have the same number of bits
  5818. if (S.Context.getTypeSize(CV->getElementType())
  5819. != S.Context.getTypeSize(ResTy)) {
  5820. // Since VectorTy is created internally, it does not pretty print
  5821. // with an OpenCL name. Instead, we just print a description.
  5822. std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
  5823. SmallString<64> Str;
  5824. llvm::raw_svector_ostream OS(Str);
  5825. OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
  5826. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5827. << CondTy << OS.str();
  5828. return QualType();
  5829. }
  5830. // Convert operands to the vector result type
  5831. LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
  5832. RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
  5833. return VectorTy;
  5834. }
  5835. /// \brief Return false if this is a valid OpenCL condition vector
  5836. static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
  5837. SourceLocation QuestionLoc) {
  5838. // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
  5839. // integral type.
  5840. const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
  5841. assert(CondTy);
  5842. QualType EleTy = CondTy->getElementType();
  5843. if (EleTy->isIntegerType()) return false;
  5844. S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
  5845. << Cond->getType() << Cond->getSourceRange();
  5846. return true;
  5847. }
  5848. /// \brief Return false if the vector condition type and the vector
  5849. /// result type are compatible.
  5850. ///
  5851. /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
  5852. /// number of elements, and their element types have the same number
  5853. /// of bits.
  5854. static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
  5855. SourceLocation QuestionLoc) {
  5856. const VectorType *CV = CondTy->getAs<VectorType>();
  5857. const VectorType *RV = VecResTy->getAs<VectorType>();
  5858. assert(CV && RV);
  5859. if (CV->getNumElements() != RV->getNumElements()) {
  5860. S.Diag(QuestionLoc, diag::err_conditional_vector_size)
  5861. << CondTy << VecResTy;
  5862. return true;
  5863. }
  5864. QualType CVE = CV->getElementType();
  5865. QualType RVE = RV->getElementType();
  5866. if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
  5867. S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
  5868. << CondTy << VecResTy;
  5869. return true;
  5870. }
  5871. return false;
  5872. }
  5873. /// \brief Return the resulting type for the conditional operator in
  5874. /// OpenCL (aka "ternary selection operator", OpenCL v1.1
  5875. /// s6.3.i) when the condition is a vector type.
  5876. static QualType
  5877. OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
  5878. ExprResult &LHS, ExprResult &RHS,
  5879. SourceLocation QuestionLoc) {
  5880. Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
  5881. if (Cond.isInvalid())
  5882. return QualType();
  5883. QualType CondTy = Cond.get()->getType();
  5884. if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
  5885. return QualType();
  5886. // If either operand is a vector then find the vector type of the
  5887. // result as specified in OpenCL v1.1 s6.3.i.
  5888. if (LHS.get()->getType()->isVectorType() ||
  5889. RHS.get()->getType()->isVectorType()) {
  5890. QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
  5891. /*isCompAssign*/false,
  5892. /*AllowBothBool*/true,
  5893. /*AllowBoolConversions*/false);
  5894. if (VecResTy.isNull()) return QualType();
  5895. // The result type must match the condition type as specified in
  5896. // OpenCL v1.1 s6.11.6.
  5897. if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
  5898. return QualType();
  5899. return VecResTy;
  5900. }
  5901. // Both operands are scalar.
  5902. return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
  5903. }
  5904. /// \brief Return true if the Expr is block type
  5905. static bool checkBlockType(Sema &S, const Expr *E) {
  5906. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  5907. QualType Ty = CE->getCallee()->getType();
  5908. if (Ty->isBlockPointerType()) {
  5909. S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
  5910. return true;
  5911. }
  5912. }
  5913. return false;
  5914. }
  5915. /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
  5916. /// In that case, LHS = cond.
  5917. /// C99 6.5.15
  5918. QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
  5919. ExprResult &RHS, ExprValueKind &VK,
  5920. ExprObjectKind &OK,
  5921. SourceLocation QuestionLoc) {
  5922. ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
  5923. if (!LHSResult.isUsable()) return QualType();
  5924. LHS = LHSResult;
  5925. ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
  5926. if (!RHSResult.isUsable()) return QualType();
  5927. RHS = RHSResult;
  5928. // C++ is sufficiently different to merit its own checker.
  5929. if (getLangOpts().CPlusPlus)
  5930. return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
  5931. VK = VK_RValue;
  5932. OK = OK_Ordinary;
  5933. // The OpenCL operator with a vector condition is sufficiently
  5934. // different to merit its own checker.
  5935. if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
  5936. return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
  5937. // First, check the condition.
  5938. Cond = UsualUnaryConversions(Cond.get());
  5939. if (Cond.isInvalid())
  5940. return QualType();
  5941. if (checkCondition(*this, Cond.get(), QuestionLoc))
  5942. return QualType();
  5943. // Now check the two expressions.
  5944. if (LHS.get()->getType()->isVectorType() ||
  5945. RHS.get()->getType()->isVectorType())
  5946. return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
  5947. /*AllowBothBool*/true,
  5948. /*AllowBoolConversions*/false);
  5949. QualType ResTy = UsualArithmeticConversions(LHS, RHS);
  5950. if (LHS.isInvalid() || RHS.isInvalid())
  5951. return QualType();
  5952. QualType LHSTy = LHS.get()->getType();
  5953. QualType RHSTy = RHS.get()->getType();
  5954. // Diagnose attempts to convert between __float128 and long double where
  5955. // such conversions currently can't be handled.
  5956. if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
  5957. Diag(QuestionLoc,
  5958. diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
  5959. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  5960. return QualType();
  5961. }
  5962. // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
  5963. // selection operator (?:).
  5964. if (getLangOpts().OpenCL &&
  5965. (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
  5966. return QualType();
  5967. }
  5968. // If both operands have arithmetic type, do the usual arithmetic conversions
  5969. // to find a common type: C99 6.5.15p3,5.
  5970. if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
  5971. LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
  5972. RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
  5973. return ResTy;
  5974. }
  5975. // If both operands are the same structure or union type, the result is that
  5976. // type.
  5977. if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
  5978. if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
  5979. if (LHSRT->getDecl() == RHSRT->getDecl())
  5980. // "If both the operands have structure or union type, the result has
  5981. // that type." This implies that CV qualifiers are dropped.
  5982. return LHSTy.getUnqualifiedType();
  5983. // FIXME: Type of conditional expression must be complete in C mode.
  5984. }
  5985. // C99 6.5.15p5: "If both operands have void type, the result has void type."
  5986. // The following || allows only one side to be void (a GCC-ism).
  5987. if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
  5988. return checkConditionalVoidType(*this, LHS, RHS);
  5989. }
  5990. // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
  5991. // the type of the other operand."
  5992. if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
  5993. if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
  5994. // All objective-c pointer type analysis is done here.
  5995. QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
  5996. QuestionLoc);
  5997. if (LHS.isInvalid() || RHS.isInvalid())
  5998. return QualType();
  5999. if (!compositeType.isNull())
  6000. return compositeType;
  6001. // Handle block pointer types.
  6002. if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
  6003. return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
  6004. QuestionLoc);
  6005. // Check constraints for C object pointers types (C99 6.5.15p3,6).
  6006. if (LHSTy->isPointerType() && RHSTy->isPointerType())
  6007. return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
  6008. QuestionLoc);
  6009. // GCC compatibility: soften pointer/integer mismatch. Note that
  6010. // null pointers have been filtered out by this point.
  6011. if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
  6012. /*isIntFirstExpr=*/true))
  6013. return RHSTy;
  6014. if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
  6015. /*isIntFirstExpr=*/false))
  6016. return LHSTy;
  6017. // Emit a better diagnostic if one of the expressions is a null pointer
  6018. // constant and the other is not a pointer type. In this case, the user most
  6019. // likely forgot to take the address of the other expression.
  6020. if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
  6021. return QualType();
  6022. // Otherwise, the operands are not compatible.
  6023. Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
  6024. << LHSTy << RHSTy << LHS.get()->getSourceRange()
  6025. << RHS.get()->getSourceRange();
  6026. return QualType();
  6027. }
  6028. /// FindCompositeObjCPointerType - Helper method to find composite type of
  6029. /// two objective-c pointer types of the two input expressions.
  6030. QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
  6031. SourceLocation QuestionLoc) {
  6032. QualType LHSTy = LHS.get()->getType();
  6033. QualType RHSTy = RHS.get()->getType();
  6034. // Handle things like Class and struct objc_class*. Here we case the result
  6035. // to the pseudo-builtin, because that will be implicitly cast back to the
  6036. // redefinition type if an attempt is made to access its fields.
  6037. if (LHSTy->isObjCClassType() &&
  6038. (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
  6039. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6040. return LHSTy;
  6041. }
  6042. if (RHSTy->isObjCClassType() &&
  6043. (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
  6044. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6045. return RHSTy;
  6046. }
  6047. // And the same for struct objc_object* / id
  6048. if (LHSTy->isObjCIdType() &&
  6049. (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
  6050. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
  6051. return LHSTy;
  6052. }
  6053. if (RHSTy->isObjCIdType() &&
  6054. (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
  6055. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
  6056. return RHSTy;
  6057. }
  6058. // And the same for struct objc_selector* / SEL
  6059. if (Context.isObjCSelType(LHSTy) &&
  6060. (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
  6061. RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
  6062. return LHSTy;
  6063. }
  6064. if (Context.isObjCSelType(RHSTy) &&
  6065. (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
  6066. LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
  6067. return RHSTy;
  6068. }
  6069. // Check constraints for Objective-C object pointers types.
  6070. if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
  6071. if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
  6072. // Two identical object pointer types are always compatible.
  6073. return LHSTy;
  6074. }
  6075. const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
  6076. const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
  6077. QualType compositeType = LHSTy;
  6078. // If both operands are interfaces and either operand can be
  6079. // assigned to the other, use that type as the composite
  6080. // type. This allows
  6081. // xxx ? (A*) a : (B*) b
  6082. // where B is a subclass of A.
  6083. //
  6084. // Additionally, as for assignment, if either type is 'id'
  6085. // allow silent coercion. Finally, if the types are
  6086. // incompatible then make sure to use 'id' as the composite
  6087. // type so the result is acceptable for sending messages to.
  6088. // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
  6089. // It could return the composite type.
  6090. if (!(compositeType =
  6091. Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
  6092. // Nothing more to do.
  6093. } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
  6094. compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
  6095. } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
  6096. compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
  6097. } else if ((LHSTy->isObjCQualifiedIdType() ||
  6098. RHSTy->isObjCQualifiedIdType()) &&
  6099. Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
  6100. // Need to handle "id<xx>" explicitly.
  6101. // GCC allows qualified id and any Objective-C type to devolve to
  6102. // id. Currently localizing to here until clear this should be
  6103. // part of ObjCQualifiedIdTypesAreCompatible.
  6104. compositeType = Context.getObjCIdType();
  6105. } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
  6106. compositeType = Context.getObjCIdType();
  6107. } else {
  6108. Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
  6109. << LHSTy << RHSTy
  6110. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6111. QualType incompatTy = Context.getObjCIdType();
  6112. LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
  6113. RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
  6114. return incompatTy;
  6115. }
  6116. // The object pointer types are compatible.
  6117. LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
  6118. RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
  6119. return compositeType;
  6120. }
  6121. // Check Objective-C object pointer types and 'void *'
  6122. if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
  6123. if (getLangOpts().ObjCAutoRefCount) {
  6124. // ARC forbids the implicit conversion of object pointers to 'void *',
  6125. // so these types are not compatible.
  6126. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6127. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6128. LHS = RHS = true;
  6129. return QualType();
  6130. }
  6131. QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
  6132. QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6133. QualType destPointee
  6134. = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
  6135. QualType destType = Context.getPointerType(destPointee);
  6136. // Add qualifiers if necessary.
  6137. LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
  6138. // Promote to void*.
  6139. RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
  6140. return destType;
  6141. }
  6142. if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
  6143. if (getLangOpts().ObjCAutoRefCount) {
  6144. // ARC forbids the implicit conversion of object pointers to 'void *',
  6145. // so these types are not compatible.
  6146. Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
  6147. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  6148. LHS = RHS = true;
  6149. return QualType();
  6150. }
  6151. QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
  6152. QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
  6153. QualType destPointee
  6154. = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
  6155. QualType destType = Context.getPointerType(destPointee);
  6156. // Add qualifiers if necessary.
  6157. RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
  6158. // Promote to void*.
  6159. LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
  6160. return destType;
  6161. }
  6162. return QualType();
  6163. }
  6164. /// SuggestParentheses - Emit a note with a fixit hint that wraps
  6165. /// ParenRange in parentheses.
  6166. static void SuggestParentheses(Sema &Self, SourceLocation Loc,
  6167. const PartialDiagnostic &Note,
  6168. SourceRange ParenRange) {
  6169. SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
  6170. if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
  6171. EndLoc.isValid()) {
  6172. Self.Diag(Loc, Note)
  6173. << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
  6174. << FixItHint::CreateInsertion(EndLoc, ")");
  6175. } else {
  6176. // We can't display the parentheses, so just show the bare note.
  6177. Self.Diag(Loc, Note) << ParenRange;
  6178. }
  6179. }
  6180. static bool IsArithmeticOp(BinaryOperatorKind Opc) {
  6181. return BinaryOperator::isAdditiveOp(Opc) ||
  6182. BinaryOperator::isMultiplicativeOp(Opc) ||
  6183. BinaryOperator::isShiftOp(Opc);
  6184. }
  6185. /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
  6186. /// expression, either using a built-in or overloaded operator,
  6187. /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
  6188. /// expression.
  6189. static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
  6190. Expr **RHSExprs) {
  6191. // Don't strip parenthesis: we should not warn if E is in parenthesis.
  6192. E = E->IgnoreImpCasts();
  6193. E = E->IgnoreConversionOperator();
  6194. E = E->IgnoreImpCasts();
  6195. // Built-in binary operator.
  6196. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
  6197. if (IsArithmeticOp(OP->getOpcode())) {
  6198. *Opcode = OP->getOpcode();
  6199. *RHSExprs = OP->getRHS();
  6200. return true;
  6201. }
  6202. }
  6203. // Overloaded operator.
  6204. if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
  6205. if (Call->getNumArgs() != 2)
  6206. return false;
  6207. // Make sure this is really a binary operator that is safe to pass into
  6208. // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
  6209. OverloadedOperatorKind OO = Call->getOperator();
  6210. if (OO < OO_Plus || OO > OO_Arrow ||
  6211. OO == OO_PlusPlus || OO == OO_MinusMinus)
  6212. return false;
  6213. BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
  6214. if (IsArithmeticOp(OpKind)) {
  6215. *Opcode = OpKind;
  6216. *RHSExprs = Call->getArg(1);
  6217. return true;
  6218. }
  6219. }
  6220. return false;
  6221. }
  6222. /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
  6223. /// or is a logical expression such as (x==y) which has int type, but is
  6224. /// commonly interpreted as boolean.
  6225. static bool ExprLooksBoolean(Expr *E) {
  6226. E = E->IgnoreParenImpCasts();
  6227. if (E->getType()->isBooleanType())
  6228. return true;
  6229. if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
  6230. return OP->isComparisonOp() || OP->isLogicalOp();
  6231. if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
  6232. return OP->getOpcode() == UO_LNot;
  6233. if (E->getType()->isPointerType())
  6234. return true;
  6235. return false;
  6236. }
  6237. /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
  6238. /// and binary operator are mixed in a way that suggests the programmer assumed
  6239. /// the conditional operator has higher precedence, for example:
  6240. /// "int x = a + someBinaryCondition ? 1 : 2".
  6241. static void DiagnoseConditionalPrecedence(Sema &Self,
  6242. SourceLocation OpLoc,
  6243. Expr *Condition,
  6244. Expr *LHSExpr,
  6245. Expr *RHSExpr) {
  6246. BinaryOperatorKind CondOpcode;
  6247. Expr *CondRHS;
  6248. if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
  6249. return;
  6250. if (!ExprLooksBoolean(CondRHS))
  6251. return;
  6252. // The condition is an arithmetic binary expression, with a right-
  6253. // hand side that looks boolean, so warn.
  6254. Self.Diag(OpLoc, diag::warn_precedence_conditional)
  6255. << Condition->getSourceRange()
  6256. << BinaryOperator::getOpcodeStr(CondOpcode);
  6257. SuggestParentheses(Self, OpLoc,
  6258. Self.PDiag(diag::note_precedence_silence)
  6259. << BinaryOperator::getOpcodeStr(CondOpcode),
  6260. SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
  6261. SuggestParentheses(Self, OpLoc,
  6262. Self.PDiag(diag::note_precedence_conditional_first),
  6263. SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
  6264. }
  6265. /// Compute the nullability of a conditional expression.
  6266. static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
  6267. QualType LHSTy, QualType RHSTy,
  6268. ASTContext &Ctx) {
  6269. if (!ResTy->isAnyPointerType())
  6270. return ResTy;
  6271. auto GetNullability = [&Ctx](QualType Ty) {
  6272. Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
  6273. if (Kind)
  6274. return *Kind;
  6275. return NullabilityKind::Unspecified;
  6276. };
  6277. auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
  6278. NullabilityKind MergedKind;
  6279. // Compute nullability of a binary conditional expression.
  6280. if (IsBin) {
  6281. if (LHSKind == NullabilityKind::NonNull)
  6282. MergedKind = NullabilityKind::NonNull;
  6283. else
  6284. MergedKind = RHSKind;
  6285. // Compute nullability of a normal conditional expression.
  6286. } else {
  6287. if (LHSKind == NullabilityKind::Nullable ||
  6288. RHSKind == NullabilityKind::Nullable)
  6289. MergedKind = NullabilityKind::Nullable;
  6290. else if (LHSKind == NullabilityKind::NonNull)
  6291. MergedKind = RHSKind;
  6292. else if (RHSKind == NullabilityKind::NonNull)
  6293. MergedKind = LHSKind;
  6294. else
  6295. MergedKind = NullabilityKind::Unspecified;
  6296. }
  6297. // Return if ResTy already has the correct nullability.
  6298. if (GetNullability(ResTy) == MergedKind)
  6299. return ResTy;
  6300. // Strip all nullability from ResTy.
  6301. while (ResTy->getNullability(Ctx))
  6302. ResTy = ResTy.getSingleStepDesugaredType(Ctx);
  6303. // Create a new AttributedType with the new nullability kind.
  6304. auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
  6305. return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
  6306. }
  6307. /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
  6308. /// in the case of a the GNU conditional expr extension.
  6309. ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
  6310. SourceLocation ColonLoc,
  6311. Expr *CondExpr, Expr *LHSExpr,
  6312. Expr *RHSExpr) {
  6313. if (!getLangOpts().CPlusPlus) {
  6314. // C cannot handle TypoExpr nodes in the condition because it
  6315. // doesn't handle dependent types properly, so make sure any TypoExprs have
  6316. // been dealt with before checking the operands.
  6317. ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
  6318. ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
  6319. ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
  6320. if (!CondResult.isUsable())
  6321. return ExprError();
  6322. if (LHSExpr) {
  6323. if (!LHSResult.isUsable())
  6324. return ExprError();
  6325. }
  6326. if (!RHSResult.isUsable())
  6327. return ExprError();
  6328. CondExpr = CondResult.get();
  6329. LHSExpr = LHSResult.get();
  6330. RHSExpr = RHSResult.get();
  6331. }
  6332. // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
  6333. // was the condition.
  6334. OpaqueValueExpr *opaqueValue = nullptr;
  6335. Expr *commonExpr = nullptr;
  6336. if (!LHSExpr) {
  6337. commonExpr = CondExpr;
  6338. // Lower out placeholder types first. This is important so that we don't
  6339. // try to capture a placeholder. This happens in few cases in C++; such
  6340. // as Objective-C++'s dictionary subscripting syntax.
  6341. if (commonExpr->hasPlaceholderType()) {
  6342. ExprResult result = CheckPlaceholderExpr(commonExpr);
  6343. if (!result.isUsable()) return ExprError();
  6344. commonExpr = result.get();
  6345. }
  6346. // We usually want to apply unary conversions *before* saving, except
  6347. // in the special case of a C++ l-value conditional.
  6348. if (!(getLangOpts().CPlusPlus
  6349. && !commonExpr->isTypeDependent()
  6350. && commonExpr->getValueKind() == RHSExpr->getValueKind()
  6351. && commonExpr->isGLValue()
  6352. && commonExpr->isOrdinaryOrBitFieldObject()
  6353. && RHSExpr->isOrdinaryOrBitFieldObject()
  6354. && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
  6355. ExprResult commonRes = UsualUnaryConversions(commonExpr);
  6356. if (commonRes.isInvalid())
  6357. return ExprError();
  6358. commonExpr = commonRes.get();
  6359. }
  6360. // If the common expression is a class or array prvalue, materialize it
  6361. // so that we can safely refer to it multiple times.
  6362. if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
  6363. commonExpr->getType()->isArrayType())) {
  6364. ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
  6365. if (MatExpr.isInvalid())
  6366. return ExprError();
  6367. commonExpr = MatExpr.get();
  6368. }
  6369. opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
  6370. commonExpr->getType(),
  6371. commonExpr->getValueKind(),
  6372. commonExpr->getObjectKind(),
  6373. commonExpr);
  6374. LHSExpr = CondExpr = opaqueValue;
  6375. }
  6376. QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
  6377. ExprValueKind VK = VK_RValue;
  6378. ExprObjectKind OK = OK_Ordinary;
  6379. ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
  6380. QualType result = CheckConditionalOperands(Cond, LHS, RHS,
  6381. VK, OK, QuestionLoc);
  6382. if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
  6383. RHS.isInvalid())
  6384. return ExprError();
  6385. DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
  6386. RHS.get());
  6387. CheckBoolLikeConversion(Cond.get(), QuestionLoc);
  6388. result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
  6389. Context);
  6390. if (!commonExpr)
  6391. return new (Context)
  6392. ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
  6393. RHS.get(), result, VK, OK);
  6394. return new (Context) BinaryConditionalOperator(
  6395. commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
  6396. ColonLoc, result, VK, OK);
  6397. }
  6398. // checkPointerTypesForAssignment - This is a very tricky routine (despite
  6399. // being closely modeled after the C99 spec:-). The odd characteristic of this
  6400. // routine is it effectively iqnores the qualifiers on the top level pointee.
  6401. // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
  6402. // FIXME: add a couple examples in this comment.
  6403. static Sema::AssignConvertType
  6404. checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
  6405. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6406. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6407. // get the "pointed to" type (ignoring qualifiers at the top level)
  6408. const Type *lhptee, *rhptee;
  6409. Qualifiers lhq, rhq;
  6410. std::tie(lhptee, lhq) =
  6411. cast<PointerType>(LHSType)->getPointeeType().split().asPair();
  6412. std::tie(rhptee, rhq) =
  6413. cast<PointerType>(RHSType)->getPointeeType().split().asPair();
  6414. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6415. // C99 6.5.16.1p1: This following citation is common to constraints
  6416. // 3 & 4 (below). ...and the type *pointed to* by the left has all the
  6417. // qualifiers of the type *pointed to* by the right;
  6418. // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
  6419. if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
  6420. lhq.compatiblyIncludesObjCLifetime(rhq)) {
  6421. // Ignore lifetime for further calculation.
  6422. lhq.removeObjCLifetime();
  6423. rhq.removeObjCLifetime();
  6424. }
  6425. if (!lhq.compatiblyIncludes(rhq)) {
  6426. // Treat address-space mismatches as fatal. TODO: address subspaces
  6427. if (!lhq.isAddressSpaceSupersetOf(rhq))
  6428. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6429. // It's okay to add or remove GC or lifetime qualifiers when converting to
  6430. // and from void*.
  6431. else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
  6432. .compatiblyIncludes(
  6433. rhq.withoutObjCGCAttr().withoutObjCLifetime())
  6434. && (lhptee->isVoidType() || rhptee->isVoidType()))
  6435. ; // keep old
  6436. // Treat lifetime mismatches as fatal.
  6437. else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
  6438. ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
  6439. // For GCC/MS compatibility, other qualifier mismatches are treated
  6440. // as still compatible in C.
  6441. else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6442. }
  6443. // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
  6444. // incomplete type and the other is a pointer to a qualified or unqualified
  6445. // version of void...
  6446. if (lhptee->isVoidType()) {
  6447. if (rhptee->isIncompleteOrObjectType())
  6448. return ConvTy;
  6449. // As an extension, we allow cast to/from void* to function pointer.
  6450. assert(rhptee->isFunctionType());
  6451. return Sema::FunctionVoidPointer;
  6452. }
  6453. if (rhptee->isVoidType()) {
  6454. if (lhptee->isIncompleteOrObjectType())
  6455. return ConvTy;
  6456. // As an extension, we allow cast to/from void* to function pointer.
  6457. assert(lhptee->isFunctionType());
  6458. return Sema::FunctionVoidPointer;
  6459. }
  6460. // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
  6461. // unqualified versions of compatible types, ...
  6462. QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
  6463. if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
  6464. // Check if the pointee types are compatible ignoring the sign.
  6465. // We explicitly check for char so that we catch "char" vs
  6466. // "unsigned char" on systems where "char" is unsigned.
  6467. if (lhptee->isCharType())
  6468. ltrans = S.Context.UnsignedCharTy;
  6469. else if (lhptee->hasSignedIntegerRepresentation())
  6470. ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
  6471. if (rhptee->isCharType())
  6472. rtrans = S.Context.UnsignedCharTy;
  6473. else if (rhptee->hasSignedIntegerRepresentation())
  6474. rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
  6475. if (ltrans == rtrans) {
  6476. // Types are compatible ignoring the sign. Qualifier incompatibility
  6477. // takes priority over sign incompatibility because the sign
  6478. // warning can be disabled.
  6479. if (ConvTy != Sema::Compatible)
  6480. return ConvTy;
  6481. return Sema::IncompatiblePointerSign;
  6482. }
  6483. // If we are a multi-level pointer, it's possible that our issue is simply
  6484. // one of qualification - e.g. char ** -> const char ** is not allowed. If
  6485. // the eventual target type is the same and the pointers have the same
  6486. // level of indirection, this must be the issue.
  6487. if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
  6488. do {
  6489. lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
  6490. rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
  6491. } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
  6492. if (lhptee == rhptee)
  6493. return Sema::IncompatibleNestedPointerQualifiers;
  6494. }
  6495. // General pointer incompatibility takes priority over qualifiers.
  6496. return Sema::IncompatiblePointer;
  6497. }
  6498. if (!S.getLangOpts().CPlusPlus &&
  6499. S.IsFunctionConversion(ltrans, rtrans, ltrans))
  6500. return Sema::IncompatiblePointer;
  6501. return ConvTy;
  6502. }
  6503. /// checkBlockPointerTypesForAssignment - This routine determines whether two
  6504. /// block pointer types are compatible or whether a block and normal pointer
  6505. /// are compatible. It is more restrict than comparing two function pointer
  6506. // types.
  6507. static Sema::AssignConvertType
  6508. checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
  6509. QualType RHSType) {
  6510. assert(LHSType.isCanonical() && "LHS not canonicalized!");
  6511. assert(RHSType.isCanonical() && "RHS not canonicalized!");
  6512. QualType lhptee, rhptee;
  6513. // get the "pointed to" type (ignoring qualifiers at the top level)
  6514. lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
  6515. rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
  6516. // In C++, the types have to match exactly.
  6517. if (S.getLangOpts().CPlusPlus)
  6518. return Sema::IncompatibleBlockPointer;
  6519. Sema::AssignConvertType ConvTy = Sema::Compatible;
  6520. // For blocks we enforce that qualifiers are identical.
  6521. Qualifiers LQuals = lhptee.getLocalQualifiers();
  6522. Qualifiers RQuals = rhptee.getLocalQualifiers();
  6523. if (S.getLangOpts().OpenCL) {
  6524. LQuals.removeAddressSpace();
  6525. RQuals.removeAddressSpace();
  6526. }
  6527. if (LQuals != RQuals)
  6528. ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
  6529. // FIXME: OpenCL doesn't define the exact compile time semantics for a block
  6530. // assignment.
  6531. // The current behavior is similar to C++ lambdas. A block might be
  6532. // assigned to a variable iff its return type and parameters are compatible
  6533. // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
  6534. // an assignment. Presumably it should behave in way that a function pointer
  6535. // assignment does in C, so for each parameter and return type:
  6536. // * CVR and address space of LHS should be a superset of CVR and address
  6537. // space of RHS.
  6538. // * unqualified types should be compatible.
  6539. if (S.getLangOpts().OpenCL) {
  6540. if (!S.Context.typesAreBlockPointerCompatible(
  6541. S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
  6542. S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
  6543. return Sema::IncompatibleBlockPointer;
  6544. } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
  6545. return Sema::IncompatibleBlockPointer;
  6546. return ConvTy;
  6547. }
  6548. /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
  6549. /// for assignment compatibility.
  6550. static Sema::AssignConvertType
  6551. checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
  6552. QualType RHSType) {
  6553. assert(LHSType.isCanonical() && "LHS was not canonicalized!");
  6554. assert(RHSType.isCanonical() && "RHS was not canonicalized!");
  6555. if (LHSType->isObjCBuiltinType()) {
  6556. // Class is not compatible with ObjC object pointers.
  6557. if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
  6558. !RHSType->isObjCQualifiedClassType())
  6559. return Sema::IncompatiblePointer;
  6560. return Sema::Compatible;
  6561. }
  6562. if (RHSType->isObjCBuiltinType()) {
  6563. if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
  6564. !LHSType->isObjCQualifiedClassType())
  6565. return Sema::IncompatiblePointer;
  6566. return Sema::Compatible;
  6567. }
  6568. QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6569. QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
  6570. if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
  6571. // make an exception for id<P>
  6572. !LHSType->isObjCQualifiedIdType())
  6573. return Sema::CompatiblePointerDiscardsQualifiers;
  6574. if (S.Context.typesAreCompatible(LHSType, RHSType))
  6575. return Sema::Compatible;
  6576. if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
  6577. return Sema::IncompatibleObjCQualifiedId;
  6578. return Sema::IncompatiblePointer;
  6579. }
  6580. Sema::AssignConvertType
  6581. Sema::CheckAssignmentConstraints(SourceLocation Loc,
  6582. QualType LHSType, QualType RHSType) {
  6583. // Fake up an opaque expression. We don't actually care about what
  6584. // cast operations are required, so if CheckAssignmentConstraints
  6585. // adds casts to this they'll be wasted, but fortunately that doesn't
  6586. // usually happen on valid code.
  6587. OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
  6588. ExprResult RHSPtr = &RHSExpr;
  6589. CastKind K;
  6590. return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
  6591. }
  6592. /// This helper function returns true if QT is a vector type that has element
  6593. /// type ElementType.
  6594. static bool isVector(QualType QT, QualType ElementType) {
  6595. if (const VectorType *VT = QT->getAs<VectorType>())
  6596. return VT->getElementType() == ElementType;
  6597. return false;
  6598. }
  6599. /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
  6600. /// has code to accommodate several GCC extensions when type checking
  6601. /// pointers. Here are some objectionable examples that GCC considers warnings:
  6602. ///
  6603. /// int a, *pint;
  6604. /// short *pshort;
  6605. /// struct foo *pfoo;
  6606. ///
  6607. /// pint = pshort; // warning: assignment from incompatible pointer type
  6608. /// a = pint; // warning: assignment makes integer from pointer without a cast
  6609. /// pint = a; // warning: assignment makes pointer from integer without a cast
  6610. /// pint = pfoo; // warning: assignment from incompatible pointer type
  6611. ///
  6612. /// As a result, the code for dealing with pointers is more complex than the
  6613. /// C99 spec dictates.
  6614. ///
  6615. /// Sets 'Kind' for any result kind except Incompatible.
  6616. Sema::AssignConvertType
  6617. Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
  6618. CastKind &Kind, bool ConvertRHS) {
  6619. QualType RHSType = RHS.get()->getType();
  6620. QualType OrigLHSType = LHSType;
  6621. // Get canonical types. We're not formatting these types, just comparing
  6622. // them.
  6623. LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
  6624. RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
  6625. // Common case: no conversion required.
  6626. if (LHSType == RHSType) {
  6627. Kind = CK_NoOp;
  6628. return Compatible;
  6629. }
  6630. // If we have an atomic type, try a non-atomic assignment, then just add an
  6631. // atomic qualification step.
  6632. if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
  6633. Sema::AssignConvertType result =
  6634. CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
  6635. if (result != Compatible)
  6636. return result;
  6637. if (Kind != CK_NoOp && ConvertRHS)
  6638. RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
  6639. Kind = CK_NonAtomicToAtomic;
  6640. return Compatible;
  6641. }
  6642. // If the left-hand side is a reference type, then we are in a
  6643. // (rare!) case where we've allowed the use of references in C,
  6644. // e.g., as a parameter type in a built-in function. In this case,
  6645. // just make sure that the type referenced is compatible with the
  6646. // right-hand side type. The caller is responsible for adjusting
  6647. // LHSType so that the resulting expression does not have reference
  6648. // type.
  6649. if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
  6650. if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
  6651. Kind = CK_LValueBitCast;
  6652. return Compatible;
  6653. }
  6654. return Incompatible;
  6655. }
  6656. // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
  6657. // to the same ExtVector type.
  6658. if (LHSType->isExtVectorType()) {
  6659. if (RHSType->isExtVectorType())
  6660. return Incompatible;
  6661. if (RHSType->isArithmeticType()) {
  6662. // CK_VectorSplat does T -> vector T, so first cast to the element type.
  6663. if (ConvertRHS)
  6664. RHS = prepareVectorSplat(LHSType, RHS.get());
  6665. Kind = CK_VectorSplat;
  6666. return Compatible;
  6667. }
  6668. }
  6669. // Conversions to or from vector type.
  6670. if (LHSType->isVectorType() || RHSType->isVectorType()) {
  6671. if (LHSType->isVectorType() && RHSType->isVectorType()) {
  6672. // Allow assignments of an AltiVec vector type to an equivalent GCC
  6673. // vector type and vice versa
  6674. if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  6675. Kind = CK_BitCast;
  6676. return Compatible;
  6677. }
  6678. // If we are allowing lax vector conversions, and LHS and RHS are both
  6679. // vectors, the total size only needs to be the same. This is a bitcast;
  6680. // no bits are changed but the result type is different.
  6681. if (isLaxVectorConversion(RHSType, LHSType)) {
  6682. Kind = CK_BitCast;
  6683. return IncompatibleVectors;
  6684. }
  6685. }
  6686. // When the RHS comes from another lax conversion (e.g. binops between
  6687. // scalars and vectors) the result is canonicalized as a vector. When the
  6688. // LHS is also a vector, the lax is allowed by the condition above. Handle
  6689. // the case where LHS is a scalar.
  6690. if (LHSType->isScalarType()) {
  6691. const VectorType *VecType = RHSType->getAs<VectorType>();
  6692. if (VecType && VecType->getNumElements() == 1 &&
  6693. isLaxVectorConversion(RHSType, LHSType)) {
  6694. ExprResult *VecExpr = &RHS;
  6695. *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
  6696. Kind = CK_BitCast;
  6697. return Compatible;
  6698. }
  6699. }
  6700. return Incompatible;
  6701. }
  6702. // Diagnose attempts to convert between __float128 and long double where
  6703. // such conversions currently can't be handled.
  6704. if (unsupportedTypeConversion(*this, LHSType, RHSType))
  6705. return Incompatible;
  6706. // Disallow assigning a _Complex to a real type in C++ mode since it simply
  6707. // discards the imaginary part.
  6708. if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
  6709. !LHSType->getAs<ComplexType>())
  6710. return Incompatible;
  6711. // Arithmetic conversions.
  6712. if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
  6713. !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
  6714. if (ConvertRHS)
  6715. Kind = PrepareScalarCast(RHS, LHSType);
  6716. return Compatible;
  6717. }
  6718. // Conversions to normal pointers.
  6719. if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
  6720. // U* -> T*
  6721. if (isa<PointerType>(RHSType)) {
  6722. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6723. LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
  6724. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6725. return checkPointerTypesForAssignment(*this, LHSType, RHSType);
  6726. }
  6727. // int -> T*
  6728. if (RHSType->isIntegerType()) {
  6729. Kind = CK_IntegralToPointer; // FIXME: null?
  6730. return IntToPointer;
  6731. }
  6732. // C pointers are not compatible with ObjC object pointers,
  6733. // with two exceptions:
  6734. if (isa<ObjCObjectPointerType>(RHSType)) {
  6735. // - conversions to void*
  6736. if (LHSPointer->getPointeeType()->isVoidType()) {
  6737. Kind = CK_BitCast;
  6738. return Compatible;
  6739. }
  6740. // - conversions from 'Class' to the redefinition type
  6741. if (RHSType->isObjCClassType() &&
  6742. Context.hasSameType(LHSType,
  6743. Context.getObjCClassRedefinitionType())) {
  6744. Kind = CK_BitCast;
  6745. return Compatible;
  6746. }
  6747. Kind = CK_BitCast;
  6748. return IncompatiblePointer;
  6749. }
  6750. // U^ -> void*
  6751. if (RHSType->getAs<BlockPointerType>()) {
  6752. if (LHSPointer->getPointeeType()->isVoidType()) {
  6753. LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
  6754. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  6755. ->getPointeeType()
  6756. .getAddressSpace();
  6757. Kind =
  6758. AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6759. return Compatible;
  6760. }
  6761. }
  6762. return Incompatible;
  6763. }
  6764. // Conversions to block pointers.
  6765. if (isa<BlockPointerType>(LHSType)) {
  6766. // U^ -> T^
  6767. if (RHSType->isBlockPointerType()) {
  6768. LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
  6769. ->getPointeeType()
  6770. .getAddressSpace();
  6771. LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
  6772. ->getPointeeType()
  6773. .getAddressSpace();
  6774. Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
  6775. return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
  6776. }
  6777. // int or null -> T^
  6778. if (RHSType->isIntegerType()) {
  6779. Kind = CK_IntegralToPointer; // FIXME: null
  6780. return IntToBlockPointer;
  6781. }
  6782. // id -> T^
  6783. if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
  6784. Kind = CK_AnyPointerToBlockPointerCast;
  6785. return Compatible;
  6786. }
  6787. // void* -> T^
  6788. if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
  6789. if (RHSPT->getPointeeType()->isVoidType()) {
  6790. Kind = CK_AnyPointerToBlockPointerCast;
  6791. return Compatible;
  6792. }
  6793. return Incompatible;
  6794. }
  6795. // Conversions to Objective-C pointers.
  6796. if (isa<ObjCObjectPointerType>(LHSType)) {
  6797. // A* -> B*
  6798. if (RHSType->isObjCObjectPointerType()) {
  6799. Kind = CK_BitCast;
  6800. Sema::AssignConvertType result =
  6801. checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
  6802. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  6803. result == Compatible &&
  6804. !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
  6805. result = IncompatibleObjCWeakRef;
  6806. return result;
  6807. }
  6808. // int or null -> A*
  6809. if (RHSType->isIntegerType()) {
  6810. Kind = CK_IntegralToPointer; // FIXME: null
  6811. return IntToPointer;
  6812. }
  6813. // In general, C pointers are not compatible with ObjC object pointers,
  6814. // with two exceptions:
  6815. if (isa<PointerType>(RHSType)) {
  6816. Kind = CK_CPointerToObjCPointerCast;
  6817. // - conversions from 'void*'
  6818. if (RHSType->isVoidPointerType()) {
  6819. return Compatible;
  6820. }
  6821. // - conversions to 'Class' from its redefinition type
  6822. if (LHSType->isObjCClassType() &&
  6823. Context.hasSameType(RHSType,
  6824. Context.getObjCClassRedefinitionType())) {
  6825. return Compatible;
  6826. }
  6827. return IncompatiblePointer;
  6828. }
  6829. // Only under strict condition T^ is compatible with an Objective-C pointer.
  6830. if (RHSType->isBlockPointerType() &&
  6831. LHSType->isBlockCompatibleObjCPointerType(Context)) {
  6832. if (ConvertRHS)
  6833. maybeExtendBlockObject(RHS);
  6834. Kind = CK_BlockPointerToObjCPointerCast;
  6835. return Compatible;
  6836. }
  6837. return Incompatible;
  6838. }
  6839. // Conversions from pointers that are not covered by the above.
  6840. if (isa<PointerType>(RHSType)) {
  6841. // T* -> _Bool
  6842. if (LHSType == Context.BoolTy) {
  6843. Kind = CK_PointerToBoolean;
  6844. return Compatible;
  6845. }
  6846. // T* -> int
  6847. if (LHSType->isIntegerType()) {
  6848. Kind = CK_PointerToIntegral;
  6849. return PointerToInt;
  6850. }
  6851. return Incompatible;
  6852. }
  6853. // Conversions from Objective-C pointers that are not covered by the above.
  6854. if (isa<ObjCObjectPointerType>(RHSType)) {
  6855. // T* -> _Bool
  6856. if (LHSType == Context.BoolTy) {
  6857. Kind = CK_PointerToBoolean;
  6858. return Compatible;
  6859. }
  6860. // T* -> int
  6861. if (LHSType->isIntegerType()) {
  6862. Kind = CK_PointerToIntegral;
  6863. return PointerToInt;
  6864. }
  6865. return Incompatible;
  6866. }
  6867. // struct A -> struct B
  6868. if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
  6869. if (Context.typesAreCompatible(LHSType, RHSType)) {
  6870. Kind = CK_NoOp;
  6871. return Compatible;
  6872. }
  6873. }
  6874. if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
  6875. Kind = CK_IntToOCLSampler;
  6876. return Compatible;
  6877. }
  6878. return Incompatible;
  6879. }
  6880. /// \brief Constructs a transparent union from an expression that is
  6881. /// used to initialize the transparent union.
  6882. static void ConstructTransparentUnion(Sema &S, ASTContext &C,
  6883. ExprResult &EResult, QualType UnionType,
  6884. FieldDecl *Field) {
  6885. // Build an initializer list that designates the appropriate member
  6886. // of the transparent union.
  6887. Expr *E = EResult.get();
  6888. InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
  6889. E, SourceLocation());
  6890. Initializer->setType(UnionType);
  6891. Initializer->setInitializedFieldInUnion(Field);
  6892. // Build a compound literal constructing a value of the transparent
  6893. // union type from this initializer list.
  6894. TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
  6895. EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
  6896. VK_RValue, Initializer, false);
  6897. }
  6898. Sema::AssignConvertType
  6899. Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
  6900. ExprResult &RHS) {
  6901. QualType RHSType = RHS.get()->getType();
  6902. // If the ArgType is a Union type, we want to handle a potential
  6903. // transparent_union GCC extension.
  6904. const RecordType *UT = ArgType->getAsUnionType();
  6905. if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
  6906. return Incompatible;
  6907. // The field to initialize within the transparent union.
  6908. RecordDecl *UD = UT->getDecl();
  6909. FieldDecl *InitField = nullptr;
  6910. // It's compatible if the expression matches any of the fields.
  6911. for (auto *it : UD->fields()) {
  6912. if (it->getType()->isPointerType()) {
  6913. // If the transparent union contains a pointer type, we allow:
  6914. // 1) void pointer
  6915. // 2) null pointer constant
  6916. if (RHSType->isPointerType())
  6917. if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
  6918. RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
  6919. InitField = it;
  6920. break;
  6921. }
  6922. if (RHS.get()->isNullPointerConstant(Context,
  6923. Expr::NPC_ValueDependentIsNull)) {
  6924. RHS = ImpCastExprToType(RHS.get(), it->getType(),
  6925. CK_NullToPointer);
  6926. InitField = it;
  6927. break;
  6928. }
  6929. }
  6930. CastKind Kind;
  6931. if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
  6932. == Compatible) {
  6933. RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
  6934. InitField = it;
  6935. break;
  6936. }
  6937. }
  6938. if (!InitField)
  6939. return Incompatible;
  6940. ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
  6941. return Compatible;
  6942. }
  6943. Sema::AssignConvertType
  6944. Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
  6945. bool Diagnose,
  6946. bool DiagnoseCFAudited,
  6947. bool ConvertRHS) {
  6948. // We need to be able to tell the caller whether we diagnosed a problem, if
  6949. // they ask us to issue diagnostics.
  6950. assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
  6951. // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
  6952. // we can't avoid *all* modifications at the moment, so we need some somewhere
  6953. // to put the updated value.
  6954. ExprResult LocalRHS = CallerRHS;
  6955. ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
  6956. if (getLangOpts().CPlusPlus) {
  6957. if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
  6958. // C++ 5.17p3: If the left operand is not of class type, the
  6959. // expression is implicitly converted (C++ 4) to the
  6960. // cv-unqualified type of the left operand.
  6961. QualType RHSType = RHS.get()->getType();
  6962. if (Diagnose) {
  6963. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6964. AA_Assigning);
  6965. } else {
  6966. ImplicitConversionSequence ICS =
  6967. TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6968. /*SuppressUserConversions=*/false,
  6969. /*AllowExplicit=*/false,
  6970. /*InOverloadResolution=*/false,
  6971. /*CStyle=*/false,
  6972. /*AllowObjCWritebackConversion=*/false);
  6973. if (ICS.isFailure())
  6974. return Incompatible;
  6975. RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
  6976. ICS, AA_Assigning);
  6977. }
  6978. if (RHS.isInvalid())
  6979. return Incompatible;
  6980. Sema::AssignConvertType result = Compatible;
  6981. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  6982. !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
  6983. result = IncompatibleObjCWeakRef;
  6984. return result;
  6985. }
  6986. // FIXME: Currently, we fall through and treat C++ classes like C
  6987. // structures.
  6988. // FIXME: We also fall through for atomics; not sure what should
  6989. // happen there, though.
  6990. } else if (RHS.get()->getType() == Context.OverloadTy) {
  6991. // As a set of extensions to C, we support overloading on functions. These
  6992. // functions need to be resolved here.
  6993. DeclAccessPair DAP;
  6994. if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
  6995. RHS.get(), LHSType, /*Complain=*/false, DAP))
  6996. RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
  6997. else
  6998. return Incompatible;
  6999. }
  7000. // C99 6.5.16.1p1: the left operand is a pointer and the right is
  7001. // a null pointer constant.
  7002. if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
  7003. LHSType->isBlockPointerType()) &&
  7004. RHS.get()->isNullPointerConstant(Context,
  7005. Expr::NPC_ValueDependentIsNull)) {
  7006. if (Diagnose || ConvertRHS) {
  7007. CastKind Kind;
  7008. CXXCastPath Path;
  7009. CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
  7010. /*IgnoreBaseAccess=*/false, Diagnose);
  7011. if (ConvertRHS)
  7012. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
  7013. }
  7014. return Compatible;
  7015. }
  7016. // This check seems unnatural, however it is necessary to ensure the proper
  7017. // conversion of functions/arrays. If the conversion were done for all
  7018. // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
  7019. // expressions that suppress this implicit conversion (&, sizeof).
  7020. //
  7021. // Suppress this for references: C++ 8.5.3p5.
  7022. if (!LHSType->isReferenceType()) {
  7023. // FIXME: We potentially allocate here even if ConvertRHS is false.
  7024. RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
  7025. if (RHS.isInvalid())
  7026. return Incompatible;
  7027. }
  7028. Expr *PRE = RHS.get()->IgnoreParenCasts();
  7029. if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
  7030. ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
  7031. if (PDecl && !PDecl->hasDefinition()) {
  7032. Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
  7033. Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
  7034. }
  7035. }
  7036. CastKind Kind;
  7037. Sema::AssignConvertType result =
  7038. CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
  7039. // C99 6.5.16.1p2: The value of the right operand is converted to the
  7040. // type of the assignment expression.
  7041. // CheckAssignmentConstraints allows the left-hand side to be a reference,
  7042. // so that we can use references in built-in functions even in C.
  7043. // The getNonReferenceType() call makes sure that the resulting expression
  7044. // does not have reference type.
  7045. if (result != Incompatible && RHS.get()->getType() != LHSType) {
  7046. QualType Ty = LHSType.getNonLValueExprType(Context);
  7047. Expr *E = RHS.get();
  7048. // Check for various Objective-C errors. If we are not reporting
  7049. // diagnostics and just checking for errors, e.g., during overload
  7050. // resolution, return Incompatible to indicate the failure.
  7051. if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  7052. CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
  7053. Diagnose, DiagnoseCFAudited) != ACR_okay) {
  7054. if (!Diagnose)
  7055. return Incompatible;
  7056. }
  7057. if (getLangOpts().ObjC1 &&
  7058. (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
  7059. E->getType(), E, Diagnose) ||
  7060. ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
  7061. if (!Diagnose)
  7062. return Incompatible;
  7063. // Replace the expression with a corrected version and continue so we
  7064. // can find further errors.
  7065. RHS = E;
  7066. return Compatible;
  7067. }
  7068. if (ConvertRHS)
  7069. RHS = ImpCastExprToType(E, Ty, Kind);
  7070. }
  7071. return result;
  7072. }
  7073. QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
  7074. ExprResult &RHS) {
  7075. Diag(Loc, diag::err_typecheck_invalid_operands)
  7076. << LHS.get()->getType() << RHS.get()->getType()
  7077. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7078. return QualType();
  7079. }
  7080. // Diagnose cases where a scalar was implicitly converted to a vector and
  7081. // diagnose the underlying types. Otherwise, diagnose the error
  7082. // as invalid vector logical operands for non-C++ cases.
  7083. QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
  7084. ExprResult &RHS) {
  7085. QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
  7086. QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
  7087. bool LHSNatVec = LHSType->isVectorType();
  7088. bool RHSNatVec = RHSType->isVectorType();
  7089. if (!(LHSNatVec && RHSNatVec)) {
  7090. Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
  7091. Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
  7092. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7093. << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
  7094. << Vector->getSourceRange();
  7095. return QualType();
  7096. }
  7097. Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
  7098. << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
  7099. << RHS.get()->getSourceRange();
  7100. return QualType();
  7101. }
  7102. /// Try to convert a value of non-vector type to a vector type by converting
  7103. /// the type to the element type of the vector and then performing a splat.
  7104. /// If the language is OpenCL, we only use conversions that promote scalar
  7105. /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
  7106. /// for float->int.
  7107. ///
  7108. /// OpenCL V2.0 6.2.6.p2:
  7109. /// An error shall occur if any scalar operand type has greater rank
  7110. /// than the type of the vector element.
  7111. ///
  7112. /// \param scalar - if non-null, actually perform the conversions
  7113. /// \return true if the operation fails (but without diagnosing the failure)
  7114. static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
  7115. QualType scalarTy,
  7116. QualType vectorEltTy,
  7117. QualType vectorTy,
  7118. unsigned &DiagID) {
  7119. // The conversion to apply to the scalar before splatting it,
  7120. // if necessary.
  7121. CastKind scalarCast = CK_NoOp;
  7122. if (vectorEltTy->isIntegralType(S.Context)) {
  7123. if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
  7124. (scalarTy->isIntegerType() &&
  7125. S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
  7126. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7127. return true;
  7128. }
  7129. if (!scalarTy->isIntegralType(S.Context))
  7130. return true;
  7131. scalarCast = CK_IntegralCast;
  7132. } else if (vectorEltTy->isRealFloatingType()) {
  7133. if (scalarTy->isRealFloatingType()) {
  7134. if (S.getLangOpts().OpenCL &&
  7135. S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
  7136. DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
  7137. return true;
  7138. }
  7139. scalarCast = CK_FloatingCast;
  7140. }
  7141. else if (scalarTy->isIntegralType(S.Context))
  7142. scalarCast = CK_IntegralToFloating;
  7143. else
  7144. return true;
  7145. } else {
  7146. return true;
  7147. }
  7148. // Adjust scalar if desired.
  7149. if (scalar) {
  7150. if (scalarCast != CK_NoOp)
  7151. *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
  7152. *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
  7153. }
  7154. return false;
  7155. }
  7156. /// Convert vector E to a vector with the same number of elements but different
  7157. /// element type.
  7158. static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
  7159. const auto *VecTy = E->getType()->getAs<VectorType>();
  7160. assert(VecTy && "Expression E must be a vector");
  7161. QualType NewVecTy = S.Context.getVectorType(ElementType,
  7162. VecTy->getNumElements(),
  7163. VecTy->getVectorKind());
  7164. // Look through the implicit cast. Return the subexpression if its type is
  7165. // NewVecTy.
  7166. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  7167. if (ICE->getSubExpr()->getType() == NewVecTy)
  7168. return ICE->getSubExpr();
  7169. auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
  7170. return S.ImpCastExprToType(E, NewVecTy, Cast);
  7171. }
  7172. /// Test if a (constant) integer Int can be casted to another integer type
  7173. /// IntTy without losing precision.
  7174. static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
  7175. QualType OtherIntTy) {
  7176. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7177. // Reject cases where the value of the Int is unknown as that would
  7178. // possibly cause truncation, but accept cases where the scalar can be
  7179. // demoted without loss of precision.
  7180. llvm::APSInt Result;
  7181. bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
  7182. int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
  7183. bool IntSigned = IntTy->hasSignedIntegerRepresentation();
  7184. bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
  7185. if (CstInt) {
  7186. // If the scalar is constant and is of a higher order and has more active
  7187. // bits that the vector element type, reject it.
  7188. unsigned NumBits = IntSigned
  7189. ? (Result.isNegative() ? Result.getMinSignedBits()
  7190. : Result.getActiveBits())
  7191. : Result.getActiveBits();
  7192. if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
  7193. return true;
  7194. // If the signedness of the scalar type and the vector element type
  7195. // differs and the number of bits is greater than that of the vector
  7196. // element reject it.
  7197. return (IntSigned != OtherIntSigned &&
  7198. NumBits > S.Context.getIntWidth(OtherIntTy));
  7199. }
  7200. // Reject cases where the value of the scalar is not constant and it's
  7201. // order is greater than that of the vector element type.
  7202. return (Order < 0);
  7203. }
  7204. /// Test if a (constant) integer Int can be casted to floating point type
  7205. /// FloatTy without losing precision.
  7206. static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
  7207. QualType FloatTy) {
  7208. QualType IntTy = Int->get()->getType().getUnqualifiedType();
  7209. // Determine if the integer constant can be expressed as a floating point
  7210. // number of the appropiate type.
  7211. llvm::APSInt Result;
  7212. bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
  7213. uint64_t Bits = 0;
  7214. if (CstInt) {
  7215. // Reject constants that would be truncated if they were converted to
  7216. // the floating point type. Test by simple to/from conversion.
  7217. // FIXME: Ideally the conversion to an APFloat and from an APFloat
  7218. // could be avoided if there was a convertFromAPInt method
  7219. // which could signal back if implicit truncation occurred.
  7220. llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
  7221. Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
  7222. llvm::APFloat::rmTowardZero);
  7223. llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
  7224. !IntTy->hasSignedIntegerRepresentation());
  7225. bool Ignored = false;
  7226. Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
  7227. &Ignored);
  7228. if (Result != ConvertBack)
  7229. return true;
  7230. } else {
  7231. // Reject types that cannot be fully encoded into the mantissa of
  7232. // the float.
  7233. Bits = S.Context.getTypeSize(IntTy);
  7234. unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
  7235. S.Context.getFloatTypeSemantics(FloatTy));
  7236. if (Bits > FloatPrec)
  7237. return true;
  7238. }
  7239. return false;
  7240. }
  7241. /// Attempt to convert and splat Scalar into a vector whose types matches
  7242. /// Vector following GCC conversion rules. The rule is that implicit
  7243. /// conversion can occur when Scalar can be casted to match Vector's element
  7244. /// type without causing truncation of Scalar.
  7245. static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
  7246. ExprResult *Vector) {
  7247. QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
  7248. QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
  7249. const VectorType *VT = VectorTy->getAs<VectorType>();
  7250. assert(!isa<ExtVectorType>(VT) &&
  7251. "ExtVectorTypes should not be handled here!");
  7252. QualType VectorEltTy = VT->getElementType();
  7253. // Reject cases where the vector element type or the scalar element type are
  7254. // not integral or floating point types.
  7255. if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
  7256. return true;
  7257. // The conversion to apply to the scalar before splatting it,
  7258. // if necessary.
  7259. CastKind ScalarCast = CK_NoOp;
  7260. // Accept cases where the vector elements are integers and the scalar is
  7261. // an integer.
  7262. // FIXME: Notionally if the scalar was a floating point value with a precise
  7263. // integral representation, we could cast it to an appropriate integer
  7264. // type and then perform the rest of the checks here. GCC will perform
  7265. // this conversion in some cases as determined by the input language.
  7266. // We should accept it on a language independent basis.
  7267. if (VectorEltTy->isIntegralType(S.Context) &&
  7268. ScalarTy->isIntegralType(S.Context) &&
  7269. S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
  7270. if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
  7271. return true;
  7272. ScalarCast = CK_IntegralCast;
  7273. } else if (VectorEltTy->isRealFloatingType()) {
  7274. if (ScalarTy->isRealFloatingType()) {
  7275. // Reject cases where the scalar type is not a constant and has a higher
  7276. // Order than the vector element type.
  7277. llvm::APFloat Result(0.0);
  7278. bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
  7279. int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
  7280. if (!CstScalar && Order < 0)
  7281. return true;
  7282. // If the scalar cannot be safely casted to the vector element type,
  7283. // reject it.
  7284. if (CstScalar) {
  7285. bool Truncated = false;
  7286. Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
  7287. llvm::APFloat::rmNearestTiesToEven, &Truncated);
  7288. if (Truncated)
  7289. return true;
  7290. }
  7291. ScalarCast = CK_FloatingCast;
  7292. } else if (ScalarTy->isIntegralType(S.Context)) {
  7293. if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
  7294. return true;
  7295. ScalarCast = CK_IntegralToFloating;
  7296. } else
  7297. return true;
  7298. }
  7299. // Adjust scalar if desired.
  7300. if (Scalar) {
  7301. if (ScalarCast != CK_NoOp)
  7302. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
  7303. *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
  7304. }
  7305. return false;
  7306. }
  7307. QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
  7308. SourceLocation Loc, bool IsCompAssign,
  7309. bool AllowBothBool,
  7310. bool AllowBoolConversions) {
  7311. if (!IsCompAssign) {
  7312. LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
  7313. if (LHS.isInvalid())
  7314. return QualType();
  7315. }
  7316. RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
  7317. if (RHS.isInvalid())
  7318. return QualType();
  7319. // For conversion purposes, we ignore any qualifiers.
  7320. // For example, "const float" and "float" are equivalent.
  7321. QualType LHSType = LHS.get()->getType().getUnqualifiedType();
  7322. QualType RHSType = RHS.get()->getType().getUnqualifiedType();
  7323. const VectorType *LHSVecType = LHSType->getAs<VectorType>();
  7324. const VectorType *RHSVecType = RHSType->getAs<VectorType>();
  7325. assert(LHSVecType || RHSVecType);
  7326. // AltiVec-style "vector bool op vector bool" combinations are allowed
  7327. // for some operators but not others.
  7328. if (!AllowBothBool &&
  7329. LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7330. RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  7331. return InvalidOperands(Loc, LHS, RHS);
  7332. // If the vector types are identical, return.
  7333. if (Context.hasSameType(LHSType, RHSType))
  7334. return LHSType;
  7335. // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
  7336. if (LHSVecType && RHSVecType &&
  7337. Context.areCompatibleVectorTypes(LHSType, RHSType)) {
  7338. if (isa<ExtVectorType>(LHSVecType)) {
  7339. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7340. return LHSType;
  7341. }
  7342. if (!IsCompAssign)
  7343. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7344. return RHSType;
  7345. }
  7346. // AllowBoolConversions says that bool and non-bool AltiVec vectors
  7347. // can be mixed, with the result being the non-bool type. The non-bool
  7348. // operand must have integer element type.
  7349. if (AllowBoolConversions && LHSVecType && RHSVecType &&
  7350. LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
  7351. (Context.getTypeSize(LHSVecType->getElementType()) ==
  7352. Context.getTypeSize(RHSVecType->getElementType()))) {
  7353. if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7354. LHSVecType->getElementType()->isIntegerType() &&
  7355. RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
  7356. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  7357. return LHSType;
  7358. }
  7359. if (!IsCompAssign &&
  7360. LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
  7361. RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
  7362. RHSVecType->getElementType()->isIntegerType()) {
  7363. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  7364. return RHSType;
  7365. }
  7366. }
  7367. // If there's a vector type and a scalar, try to convert the scalar to
  7368. // the vector element type and splat.
  7369. unsigned DiagID = diag::err_typecheck_vector_not_convertable;
  7370. if (!RHSVecType) {
  7371. if (isa<ExtVectorType>(LHSVecType)) {
  7372. if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
  7373. LHSVecType->getElementType(), LHSType,
  7374. DiagID))
  7375. return LHSType;
  7376. } else {
  7377. if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
  7378. return LHSType;
  7379. }
  7380. }
  7381. if (!LHSVecType) {
  7382. if (isa<ExtVectorType>(RHSVecType)) {
  7383. if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
  7384. LHSType, RHSVecType->getElementType(),
  7385. RHSType, DiagID))
  7386. return RHSType;
  7387. } else {
  7388. if (LHS.get()->getValueKind() == VK_LValue ||
  7389. !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
  7390. return RHSType;
  7391. }
  7392. }
  7393. // FIXME: The code below also handles conversion between vectors and
  7394. // non-scalars, we should break this down into fine grained specific checks
  7395. // and emit proper diagnostics.
  7396. QualType VecType = LHSVecType ? LHSType : RHSType;
  7397. const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
  7398. QualType OtherType = LHSVecType ? RHSType : LHSType;
  7399. ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
  7400. if (isLaxVectorConversion(OtherType, VecType)) {
  7401. // If we're allowing lax vector conversions, only the total (data) size
  7402. // needs to be the same. For non compound assignment, if one of the types is
  7403. // scalar, the result is always the vector type.
  7404. if (!IsCompAssign) {
  7405. *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
  7406. return VecType;
  7407. // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
  7408. // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
  7409. // type. Note that this is already done by non-compound assignments in
  7410. // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
  7411. // <1 x T> -> T. The result is also a vector type.
  7412. } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
  7413. (OtherType->isScalarType() && VT->getNumElements() == 1)) {
  7414. ExprResult *RHSExpr = &RHS;
  7415. *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
  7416. return VecType;
  7417. }
  7418. }
  7419. // Okay, the expression is invalid.
  7420. // If there's a non-vector, non-real operand, diagnose that.
  7421. if ((!RHSVecType && !RHSType->isRealType()) ||
  7422. (!LHSVecType && !LHSType->isRealType())) {
  7423. Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
  7424. << LHSType << RHSType
  7425. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7426. return QualType();
  7427. }
  7428. // OpenCL V1.1 6.2.6.p1:
  7429. // If the operands are of more than one vector type, then an error shall
  7430. // occur. Implicit conversions between vector types are not permitted, per
  7431. // section 6.2.1.
  7432. if (getLangOpts().OpenCL &&
  7433. RHSVecType && isa<ExtVectorType>(RHSVecType) &&
  7434. LHSVecType && isa<ExtVectorType>(LHSVecType)) {
  7435. Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
  7436. << RHSType;
  7437. return QualType();
  7438. }
  7439. // If there is a vector type that is not a ExtVector and a scalar, we reach
  7440. // this point if scalar could not be converted to the vector's element type
  7441. // without truncation.
  7442. if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
  7443. (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
  7444. QualType Scalar = LHSVecType ? RHSType : LHSType;
  7445. QualType Vector = LHSVecType ? LHSType : RHSType;
  7446. unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
  7447. Diag(Loc,
  7448. diag::err_typecheck_vector_not_convertable_implict_truncation)
  7449. << ScalarOrVector << Scalar << Vector;
  7450. return QualType();
  7451. }
  7452. // Otherwise, use the generic diagnostic.
  7453. Diag(Loc, DiagID)
  7454. << LHSType << RHSType
  7455. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7456. return QualType();
  7457. }
  7458. // checkArithmeticNull - Detect when a NULL constant is used improperly in an
  7459. // expression. These are mainly cases where the null pointer is used as an
  7460. // integer instead of a pointer.
  7461. static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
  7462. SourceLocation Loc, bool IsCompare) {
  7463. // The canonical way to check for a GNU null is with isNullPointerConstant,
  7464. // but we use a bit of a hack here for speed; this is a relatively
  7465. // hot path, and isNullPointerConstant is slow.
  7466. bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
  7467. bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
  7468. QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
  7469. // Avoid analyzing cases where the result will either be invalid (and
  7470. // diagnosed as such) or entirely valid and not something to warn about.
  7471. if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
  7472. NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
  7473. return;
  7474. // Comparison operations would not make sense with a null pointer no matter
  7475. // what the other expression is.
  7476. if (!IsCompare) {
  7477. S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
  7478. << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
  7479. << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
  7480. return;
  7481. }
  7482. // The rest of the operations only make sense with a null pointer
  7483. // if the other expression is a pointer.
  7484. if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
  7485. NonNullType->canDecayToPointerType())
  7486. return;
  7487. S.Diag(Loc, diag::warn_null_in_comparison_operation)
  7488. << LHSNull /* LHS is NULL */ << NonNullType
  7489. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7490. }
  7491. static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
  7492. ExprResult &RHS,
  7493. SourceLocation Loc, bool IsDiv) {
  7494. // Check for division/remainder by zero.
  7495. llvm::APSInt RHSValue;
  7496. if (!RHS.get()->isValueDependent() &&
  7497. RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
  7498. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7499. S.PDiag(diag::warn_remainder_division_by_zero)
  7500. << IsDiv << RHS.get()->getSourceRange());
  7501. }
  7502. QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
  7503. SourceLocation Loc,
  7504. bool IsCompAssign, bool IsDiv) {
  7505. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7506. if (LHS.get()->getType()->isVectorType() ||
  7507. RHS.get()->getType()->isVectorType())
  7508. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7509. /*AllowBothBool*/getLangOpts().AltiVec,
  7510. /*AllowBoolConversions*/false);
  7511. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7512. if (LHS.isInvalid() || RHS.isInvalid())
  7513. return QualType();
  7514. if (compType.isNull() || !compType->isArithmeticType())
  7515. return InvalidOperands(Loc, LHS, RHS);
  7516. if (IsDiv)
  7517. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
  7518. return compType;
  7519. }
  7520. QualType Sema::CheckRemainderOperands(
  7521. ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
  7522. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7523. if (LHS.get()->getType()->isVectorType() ||
  7524. RHS.get()->getType()->isVectorType()) {
  7525. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  7526. RHS.get()->getType()->hasIntegerRepresentation())
  7527. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  7528. /*AllowBothBool*/getLangOpts().AltiVec,
  7529. /*AllowBoolConversions*/false);
  7530. return InvalidOperands(Loc, LHS, RHS);
  7531. }
  7532. QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
  7533. if (LHS.isInvalid() || RHS.isInvalid())
  7534. return QualType();
  7535. if (compType.isNull() || !compType->isIntegerType())
  7536. return InvalidOperands(Loc, LHS, RHS);
  7537. DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
  7538. return compType;
  7539. }
  7540. /// \brief Diagnose invalid arithmetic on two void pointers.
  7541. static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
  7542. Expr *LHSExpr, Expr *RHSExpr) {
  7543. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7544. ? diag::err_typecheck_pointer_arith_void_type
  7545. : diag::ext_gnu_void_ptr)
  7546. << 1 /* two pointers */ << LHSExpr->getSourceRange()
  7547. << RHSExpr->getSourceRange();
  7548. }
  7549. /// \brief Diagnose invalid arithmetic on a void pointer.
  7550. static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
  7551. Expr *Pointer) {
  7552. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7553. ? diag::err_typecheck_pointer_arith_void_type
  7554. : diag::ext_gnu_void_ptr)
  7555. << 0 /* one pointer */ << Pointer->getSourceRange();
  7556. }
  7557. /// \brief Diagnose invalid arithmetic on a null pointer.
  7558. ///
  7559. /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
  7560. /// idiom, which we recognize as a GNU extension.
  7561. ///
  7562. static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
  7563. Expr *Pointer, bool IsGNUIdiom) {
  7564. if (IsGNUIdiom)
  7565. S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
  7566. << Pointer->getSourceRange();
  7567. else
  7568. S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
  7569. << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
  7570. }
  7571. /// \brief Diagnose invalid arithmetic on two function pointers.
  7572. static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
  7573. Expr *LHS, Expr *RHS) {
  7574. assert(LHS->getType()->isAnyPointerType());
  7575. assert(RHS->getType()->isAnyPointerType());
  7576. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7577. ? diag::err_typecheck_pointer_arith_function_type
  7578. : diag::ext_gnu_ptr_func_arith)
  7579. << 1 /* two pointers */ << LHS->getType()->getPointeeType()
  7580. // We only show the second type if it differs from the first.
  7581. << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
  7582. RHS->getType())
  7583. << RHS->getType()->getPointeeType()
  7584. << LHS->getSourceRange() << RHS->getSourceRange();
  7585. }
  7586. /// \brief Diagnose invalid arithmetic on a function pointer.
  7587. static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
  7588. Expr *Pointer) {
  7589. assert(Pointer->getType()->isAnyPointerType());
  7590. S.Diag(Loc, S.getLangOpts().CPlusPlus
  7591. ? diag::err_typecheck_pointer_arith_function_type
  7592. : diag::ext_gnu_ptr_func_arith)
  7593. << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
  7594. << 0 /* one pointer, so only one type */
  7595. << Pointer->getSourceRange();
  7596. }
  7597. /// \brief Emit error if Operand is incomplete pointer type
  7598. ///
  7599. /// \returns True if pointer has incomplete type
  7600. static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
  7601. Expr *Operand) {
  7602. QualType ResType = Operand->getType();
  7603. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7604. ResType = ResAtomicType->getValueType();
  7605. assert(ResType->isAnyPointerType() && !ResType->isDependentType());
  7606. QualType PointeeTy = ResType->getPointeeType();
  7607. return S.RequireCompleteType(Loc, PointeeTy,
  7608. diag::err_typecheck_arithmetic_incomplete_type,
  7609. PointeeTy, Operand->getSourceRange());
  7610. }
  7611. /// \brief Check the validity of an arithmetic pointer operand.
  7612. ///
  7613. /// If the operand has pointer type, this code will check for pointer types
  7614. /// which are invalid in arithmetic operations. These will be diagnosed
  7615. /// appropriately, including whether or not the use is supported as an
  7616. /// extension.
  7617. ///
  7618. /// \returns True when the operand is valid to use (even if as an extension).
  7619. static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
  7620. Expr *Operand) {
  7621. QualType ResType = Operand->getType();
  7622. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  7623. ResType = ResAtomicType->getValueType();
  7624. if (!ResType->isAnyPointerType()) return true;
  7625. QualType PointeeTy = ResType->getPointeeType();
  7626. if (PointeeTy->isVoidType()) {
  7627. diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
  7628. return !S.getLangOpts().CPlusPlus;
  7629. }
  7630. if (PointeeTy->isFunctionType()) {
  7631. diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
  7632. return !S.getLangOpts().CPlusPlus;
  7633. }
  7634. if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
  7635. return true;
  7636. }
  7637. /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
  7638. /// operands.
  7639. ///
  7640. /// This routine will diagnose any invalid arithmetic on pointer operands much
  7641. /// like \see checkArithmeticOpPointerOperand. However, it has special logic
  7642. /// for emitting a single diagnostic even for operations where both LHS and RHS
  7643. /// are (potentially problematic) pointers.
  7644. ///
  7645. /// \returns True when the operand is valid to use (even if as an extension).
  7646. static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
  7647. Expr *LHSExpr, Expr *RHSExpr) {
  7648. bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
  7649. bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
  7650. if (!isLHSPointer && !isRHSPointer) return true;
  7651. QualType LHSPointeeTy, RHSPointeeTy;
  7652. if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
  7653. if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
  7654. // if both are pointers check if operation is valid wrt address spaces
  7655. if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
  7656. const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
  7657. const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
  7658. if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
  7659. S.Diag(Loc,
  7660. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  7661. << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
  7662. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  7663. return false;
  7664. }
  7665. }
  7666. // Check for arithmetic on pointers to incomplete types.
  7667. bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
  7668. bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
  7669. if (isLHSVoidPtr || isRHSVoidPtr) {
  7670. if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
  7671. else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
  7672. else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
  7673. return !S.getLangOpts().CPlusPlus;
  7674. }
  7675. bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
  7676. bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
  7677. if (isLHSFuncPtr || isRHSFuncPtr) {
  7678. if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
  7679. else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
  7680. RHSExpr);
  7681. else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
  7682. return !S.getLangOpts().CPlusPlus;
  7683. }
  7684. if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
  7685. return false;
  7686. if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
  7687. return false;
  7688. return true;
  7689. }
  7690. /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
  7691. /// literal.
  7692. static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
  7693. Expr *LHSExpr, Expr *RHSExpr) {
  7694. StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
  7695. Expr* IndexExpr = RHSExpr;
  7696. if (!StrExpr) {
  7697. StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
  7698. IndexExpr = LHSExpr;
  7699. }
  7700. bool IsStringPlusInt = StrExpr &&
  7701. IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
  7702. if (!IsStringPlusInt || IndexExpr->isValueDependent())
  7703. return;
  7704. llvm::APSInt index;
  7705. if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
  7706. unsigned StrLenWithNull = StrExpr->getLength() + 1;
  7707. if (index.isNonNegative() &&
  7708. index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
  7709. index.isUnsigned()))
  7710. return;
  7711. }
  7712. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  7713. Self.Diag(OpLoc, diag::warn_string_plus_int)
  7714. << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
  7715. // Only print a fixit for "str" + int, not for int + "str".
  7716. if (IndexExpr == RHSExpr) {
  7717. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
  7718. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  7719. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  7720. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  7721. << FixItHint::CreateInsertion(EndLoc, "]");
  7722. } else
  7723. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  7724. }
  7725. /// \brief Emit a warning when adding a char literal to a string.
  7726. static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
  7727. Expr *LHSExpr, Expr *RHSExpr) {
  7728. const Expr *StringRefExpr = LHSExpr;
  7729. const CharacterLiteral *CharExpr =
  7730. dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
  7731. if (!CharExpr) {
  7732. CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
  7733. StringRefExpr = RHSExpr;
  7734. }
  7735. if (!CharExpr || !StringRefExpr)
  7736. return;
  7737. const QualType StringType = StringRefExpr->getType();
  7738. // Return if not a PointerType.
  7739. if (!StringType->isAnyPointerType())
  7740. return;
  7741. // Return if not a CharacterType.
  7742. if (!StringType->getPointeeType()->isAnyCharacterType())
  7743. return;
  7744. ASTContext &Ctx = Self.getASTContext();
  7745. SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  7746. const QualType CharType = CharExpr->getType();
  7747. if (!CharType->isAnyCharacterType() &&
  7748. CharType->isIntegerType() &&
  7749. llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
  7750. Self.Diag(OpLoc, diag::warn_string_plus_char)
  7751. << DiagRange << Ctx.CharTy;
  7752. } else {
  7753. Self.Diag(OpLoc, diag::warn_string_plus_char)
  7754. << DiagRange << CharExpr->getType();
  7755. }
  7756. // Only print a fixit for str + char, not for char + str.
  7757. if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
  7758. SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
  7759. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
  7760. << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
  7761. << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
  7762. << FixItHint::CreateInsertion(EndLoc, "]");
  7763. } else {
  7764. Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
  7765. }
  7766. }
  7767. /// \brief Emit error when two pointers are incompatible.
  7768. static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
  7769. Expr *LHSExpr, Expr *RHSExpr) {
  7770. assert(LHSExpr->getType()->isAnyPointerType());
  7771. assert(RHSExpr->getType()->isAnyPointerType());
  7772. S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
  7773. << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
  7774. << RHSExpr->getSourceRange();
  7775. }
  7776. // C99 6.5.6
  7777. QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
  7778. SourceLocation Loc, BinaryOperatorKind Opc,
  7779. QualType* CompLHSTy) {
  7780. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7781. if (LHS.get()->getType()->isVectorType() ||
  7782. RHS.get()->getType()->isVectorType()) {
  7783. QualType compType = CheckVectorOperands(
  7784. LHS, RHS, Loc, CompLHSTy,
  7785. /*AllowBothBool*/getLangOpts().AltiVec,
  7786. /*AllowBoolConversions*/getLangOpts().ZVector);
  7787. if (CompLHSTy) *CompLHSTy = compType;
  7788. return compType;
  7789. }
  7790. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7791. if (LHS.isInvalid() || RHS.isInvalid())
  7792. return QualType();
  7793. // Diagnose "string literal" '+' int and string '+' "char literal".
  7794. if (Opc == BO_Add) {
  7795. diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
  7796. diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
  7797. }
  7798. // handle the common case first (both operands are arithmetic).
  7799. if (!compType.isNull() && compType->isArithmeticType()) {
  7800. if (CompLHSTy) *CompLHSTy = compType;
  7801. return compType;
  7802. }
  7803. // Type-checking. Ultimately the pointer's going to be in PExp;
  7804. // note that we bias towards the LHS being the pointer.
  7805. Expr *PExp = LHS.get(), *IExp = RHS.get();
  7806. bool isObjCPointer;
  7807. if (PExp->getType()->isPointerType()) {
  7808. isObjCPointer = false;
  7809. } else if (PExp->getType()->isObjCObjectPointerType()) {
  7810. isObjCPointer = true;
  7811. } else {
  7812. std::swap(PExp, IExp);
  7813. if (PExp->getType()->isPointerType()) {
  7814. isObjCPointer = false;
  7815. } else if (PExp->getType()->isObjCObjectPointerType()) {
  7816. isObjCPointer = true;
  7817. } else {
  7818. return InvalidOperands(Loc, LHS, RHS);
  7819. }
  7820. }
  7821. assert(PExp->getType()->isAnyPointerType());
  7822. if (!IExp->getType()->isIntegerType())
  7823. return InvalidOperands(Loc, LHS, RHS);
  7824. // Adding to a null pointer results in undefined behavior.
  7825. if (PExp->IgnoreParenCasts()->isNullPointerConstant(
  7826. Context, Expr::NPC_ValueDependentIsNotNull)) {
  7827. // In C++ adding zero to a null pointer is defined.
  7828. llvm::APSInt KnownVal;
  7829. if (!getLangOpts().CPlusPlus ||
  7830. (!IExp->isValueDependent() &&
  7831. (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
  7832. // Check the conditions to see if this is the 'p = nullptr + n' idiom.
  7833. bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
  7834. Context, BO_Add, PExp, IExp);
  7835. diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
  7836. }
  7837. }
  7838. if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
  7839. return QualType();
  7840. if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
  7841. return QualType();
  7842. // Check array bounds for pointer arithemtic
  7843. CheckArrayAccess(PExp, IExp);
  7844. if (CompLHSTy) {
  7845. QualType LHSTy = Context.isPromotableBitField(LHS.get());
  7846. if (LHSTy.isNull()) {
  7847. LHSTy = LHS.get()->getType();
  7848. if (LHSTy->isPromotableIntegerType())
  7849. LHSTy = Context.getPromotedIntegerType(LHSTy);
  7850. }
  7851. *CompLHSTy = LHSTy;
  7852. }
  7853. return PExp->getType();
  7854. }
  7855. // C99 6.5.6
  7856. QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
  7857. SourceLocation Loc,
  7858. QualType* CompLHSTy) {
  7859. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  7860. if (LHS.get()->getType()->isVectorType() ||
  7861. RHS.get()->getType()->isVectorType()) {
  7862. QualType compType = CheckVectorOperands(
  7863. LHS, RHS, Loc, CompLHSTy,
  7864. /*AllowBothBool*/getLangOpts().AltiVec,
  7865. /*AllowBoolConversions*/getLangOpts().ZVector);
  7866. if (CompLHSTy) *CompLHSTy = compType;
  7867. return compType;
  7868. }
  7869. QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
  7870. if (LHS.isInvalid() || RHS.isInvalid())
  7871. return QualType();
  7872. // Enforce type constraints: C99 6.5.6p3.
  7873. // Handle the common case first (both operands are arithmetic).
  7874. if (!compType.isNull() && compType->isArithmeticType()) {
  7875. if (CompLHSTy) *CompLHSTy = compType;
  7876. return compType;
  7877. }
  7878. // Either ptr - int or ptr - ptr.
  7879. if (LHS.get()->getType()->isAnyPointerType()) {
  7880. QualType lpointee = LHS.get()->getType()->getPointeeType();
  7881. // Diagnose bad cases where we step over interface counts.
  7882. if (LHS.get()->getType()->isObjCObjectPointerType() &&
  7883. checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
  7884. return QualType();
  7885. // The result type of a pointer-int computation is the pointer type.
  7886. if (RHS.get()->getType()->isIntegerType()) {
  7887. // Subtracting from a null pointer should produce a warning.
  7888. // The last argument to the diagnose call says this doesn't match the
  7889. // GNU int-to-pointer idiom.
  7890. if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
  7891. Expr::NPC_ValueDependentIsNotNull)) {
  7892. // In C++ adding zero to a null pointer is defined.
  7893. llvm::APSInt KnownVal;
  7894. if (!getLangOpts().CPlusPlus ||
  7895. (!RHS.get()->isValueDependent() &&
  7896. (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
  7897. diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
  7898. }
  7899. }
  7900. if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
  7901. return QualType();
  7902. // Check array bounds for pointer arithemtic
  7903. CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
  7904. /*AllowOnePastEnd*/true, /*IndexNegated*/true);
  7905. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7906. return LHS.get()->getType();
  7907. }
  7908. // Handle pointer-pointer subtractions.
  7909. if (const PointerType *RHSPTy
  7910. = RHS.get()->getType()->getAs<PointerType>()) {
  7911. QualType rpointee = RHSPTy->getPointeeType();
  7912. if (getLangOpts().CPlusPlus) {
  7913. // Pointee types must be the same: C++ [expr.add]
  7914. if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
  7915. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7916. }
  7917. } else {
  7918. // Pointee types must be compatible C99 6.5.6p3
  7919. if (!Context.typesAreCompatible(
  7920. Context.getCanonicalType(lpointee).getUnqualifiedType(),
  7921. Context.getCanonicalType(rpointee).getUnqualifiedType())) {
  7922. diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
  7923. return QualType();
  7924. }
  7925. }
  7926. if (!checkArithmeticBinOpPointerOperands(*this, Loc,
  7927. LHS.get(), RHS.get()))
  7928. return QualType();
  7929. // FIXME: Add warnings for nullptr - ptr.
  7930. // The pointee type may have zero size. As an extension, a structure or
  7931. // union may have zero size or an array may have zero length. In this
  7932. // case subtraction does not make sense.
  7933. if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
  7934. CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
  7935. if (ElementSize.isZero()) {
  7936. Diag(Loc,diag::warn_sub_ptr_zero_size_types)
  7937. << rpointee.getUnqualifiedType()
  7938. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  7939. }
  7940. }
  7941. if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
  7942. return Context.getPointerDiffType();
  7943. }
  7944. }
  7945. return InvalidOperands(Loc, LHS, RHS);
  7946. }
  7947. static bool isScopedEnumerationType(QualType T) {
  7948. if (const EnumType *ET = T->getAs<EnumType>())
  7949. return ET->getDecl()->isScoped();
  7950. return false;
  7951. }
  7952. static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
  7953. SourceLocation Loc, BinaryOperatorKind Opc,
  7954. QualType LHSType) {
  7955. // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
  7956. // so skip remaining warnings as we don't want to modify values within Sema.
  7957. if (S.getLangOpts().OpenCL)
  7958. return;
  7959. llvm::APSInt Right;
  7960. // Check right/shifter operand
  7961. if (RHS.get()->isValueDependent() ||
  7962. !RHS.get()->EvaluateAsInt(Right, S.Context))
  7963. return;
  7964. if (Right.isNegative()) {
  7965. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7966. S.PDiag(diag::warn_shift_negative)
  7967. << RHS.get()->getSourceRange());
  7968. return;
  7969. }
  7970. llvm::APInt LeftBits(Right.getBitWidth(),
  7971. S.Context.getTypeSize(LHS.get()->getType()));
  7972. if (Right.uge(LeftBits)) {
  7973. S.DiagRuntimeBehavior(Loc, RHS.get(),
  7974. S.PDiag(diag::warn_shift_gt_typewidth)
  7975. << RHS.get()->getSourceRange());
  7976. return;
  7977. }
  7978. if (Opc != BO_Shl)
  7979. return;
  7980. // When left shifting an ICE which is signed, we can check for overflow which
  7981. // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
  7982. // integers have defined behavior modulo one more than the maximum value
  7983. // representable in the result type, so never warn for those.
  7984. llvm::APSInt Left;
  7985. if (LHS.get()->isValueDependent() ||
  7986. LHSType->hasUnsignedIntegerRepresentation() ||
  7987. !LHS.get()->EvaluateAsInt(Left, S.Context))
  7988. return;
  7989. // If LHS does not have a signed type and non-negative value
  7990. // then, the behavior is undefined. Warn about it.
  7991. if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
  7992. S.DiagRuntimeBehavior(Loc, LHS.get(),
  7993. S.PDiag(diag::warn_shift_lhs_negative)
  7994. << LHS.get()->getSourceRange());
  7995. return;
  7996. }
  7997. llvm::APInt ResultBits =
  7998. static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
  7999. if (LeftBits.uge(ResultBits))
  8000. return;
  8001. llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
  8002. Result = Result.shl(Right);
  8003. // Print the bit representation of the signed integer as an unsigned
  8004. // hexadecimal number.
  8005. SmallString<40> HexResult;
  8006. Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
  8007. // If we are only missing a sign bit, this is less likely to result in actual
  8008. // bugs -- if the result is cast back to an unsigned type, it will have the
  8009. // expected value. Thus we place this behind a different warning that can be
  8010. // turned off separately if needed.
  8011. if (LeftBits == ResultBits - 1) {
  8012. S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
  8013. << HexResult << LHSType
  8014. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8015. return;
  8016. }
  8017. S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
  8018. << HexResult.str() << Result.getMinSignedBits() << LHSType
  8019. << Left.getBitWidth() << LHS.get()->getSourceRange()
  8020. << RHS.get()->getSourceRange();
  8021. }
  8022. /// \brief Return the resulting type when a vector is shifted
  8023. /// by a scalar or vector shift amount.
  8024. static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
  8025. SourceLocation Loc, bool IsCompAssign) {
  8026. // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
  8027. if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
  8028. !LHS.get()->getType()->isVectorType()) {
  8029. S.Diag(Loc, diag::err_shift_rhs_only_vector)
  8030. << RHS.get()->getType() << LHS.get()->getType()
  8031. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8032. return QualType();
  8033. }
  8034. if (!IsCompAssign) {
  8035. LHS = S.UsualUnaryConversions(LHS.get());
  8036. if (LHS.isInvalid()) return QualType();
  8037. }
  8038. RHS = S.UsualUnaryConversions(RHS.get());
  8039. if (RHS.isInvalid()) return QualType();
  8040. QualType LHSType = LHS.get()->getType();
  8041. // Note that LHS might be a scalar because the routine calls not only in
  8042. // OpenCL case.
  8043. const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
  8044. QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
  8045. // Note that RHS might not be a vector.
  8046. QualType RHSType = RHS.get()->getType();
  8047. const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
  8048. QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
  8049. // The operands need to be integers.
  8050. if (!LHSEleType->isIntegerType()) {
  8051. S.Diag(Loc, diag::err_typecheck_expect_int)
  8052. << LHS.get()->getType() << LHS.get()->getSourceRange();
  8053. return QualType();
  8054. }
  8055. if (!RHSEleType->isIntegerType()) {
  8056. S.Diag(Loc, diag::err_typecheck_expect_int)
  8057. << RHS.get()->getType() << RHS.get()->getSourceRange();
  8058. return QualType();
  8059. }
  8060. if (!LHSVecTy) {
  8061. assert(RHSVecTy);
  8062. if (IsCompAssign)
  8063. return RHSType;
  8064. if (LHSEleType != RHSEleType) {
  8065. LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
  8066. LHSEleType = RHSEleType;
  8067. }
  8068. QualType VecTy =
  8069. S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
  8070. LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
  8071. LHSType = VecTy;
  8072. } else if (RHSVecTy) {
  8073. // OpenCL v1.1 s6.3.j says that for vector types, the operators
  8074. // are applied component-wise. So if RHS is a vector, then ensure
  8075. // that the number of elements is the same as LHS...
  8076. if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
  8077. S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
  8078. << LHS.get()->getType() << RHS.get()->getType()
  8079. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8080. return QualType();
  8081. }
  8082. if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
  8083. const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
  8084. const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
  8085. if (LHSBT != RHSBT &&
  8086. S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
  8087. S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
  8088. << LHS.get()->getType() << RHS.get()->getType()
  8089. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8090. }
  8091. }
  8092. } else {
  8093. // ...else expand RHS to match the number of elements in LHS.
  8094. QualType VecTy =
  8095. S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
  8096. RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
  8097. }
  8098. return LHSType;
  8099. }
  8100. // C99 6.5.7
  8101. QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
  8102. SourceLocation Loc, BinaryOperatorKind Opc,
  8103. bool IsCompAssign) {
  8104. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8105. // Vector shifts promote their scalar inputs to vector type.
  8106. if (LHS.get()->getType()->isVectorType() ||
  8107. RHS.get()->getType()->isVectorType()) {
  8108. if (LangOpts.ZVector) {
  8109. // The shift operators for the z vector extensions work basically
  8110. // like general shifts, except that neither the LHS nor the RHS is
  8111. // allowed to be a "vector bool".
  8112. if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
  8113. if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8114. return InvalidOperands(Loc, LHS, RHS);
  8115. if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
  8116. if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
  8117. return InvalidOperands(Loc, LHS, RHS);
  8118. }
  8119. return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
  8120. }
  8121. // Shifts don't perform usual arithmetic conversions, they just do integer
  8122. // promotions on each operand. C99 6.5.7p3
  8123. // For the LHS, do usual unary conversions, but then reset them away
  8124. // if this is a compound assignment.
  8125. ExprResult OldLHS = LHS;
  8126. LHS = UsualUnaryConversions(LHS.get());
  8127. if (LHS.isInvalid())
  8128. return QualType();
  8129. QualType LHSType = LHS.get()->getType();
  8130. if (IsCompAssign) LHS = OldLHS;
  8131. // The RHS is simpler.
  8132. RHS = UsualUnaryConversions(RHS.get());
  8133. if (RHS.isInvalid())
  8134. return QualType();
  8135. QualType RHSType = RHS.get()->getType();
  8136. // C99 6.5.7p2: Each of the operands shall have integer type.
  8137. if (!LHSType->hasIntegerRepresentation() ||
  8138. !RHSType->hasIntegerRepresentation())
  8139. return InvalidOperands(Loc, LHS, RHS);
  8140. // C++0x: Don't allow scoped enums. FIXME: Use something better than
  8141. // hasIntegerRepresentation() above instead of this.
  8142. if (isScopedEnumerationType(LHSType) ||
  8143. isScopedEnumerationType(RHSType)) {
  8144. return InvalidOperands(Loc, LHS, RHS);
  8145. }
  8146. // Sanity-check shift operands
  8147. DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
  8148. // "The type of the result is that of the promoted left operand."
  8149. return LHSType;
  8150. }
  8151. static bool IsWithinTemplateSpecialization(Decl *D) {
  8152. if (DeclContext *DC = D->getDeclContext()) {
  8153. if (isa<ClassTemplateSpecializationDecl>(DC))
  8154. return true;
  8155. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
  8156. return FD->isFunctionTemplateSpecialization();
  8157. }
  8158. return false;
  8159. }
  8160. /// If two different enums are compared, raise a warning.
  8161. static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
  8162. Expr *RHS) {
  8163. QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
  8164. QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
  8165. const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
  8166. if (!LHSEnumType)
  8167. return;
  8168. const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
  8169. if (!RHSEnumType)
  8170. return;
  8171. // Ignore anonymous enums.
  8172. if (!LHSEnumType->getDecl()->getIdentifier() &&
  8173. !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8174. return;
  8175. if (!RHSEnumType->getDecl()->getIdentifier() &&
  8176. !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
  8177. return;
  8178. if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
  8179. return;
  8180. S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
  8181. << LHSStrippedType << RHSStrippedType
  8182. << LHS->getSourceRange() << RHS->getSourceRange();
  8183. }
  8184. /// \brief Diagnose bad pointer comparisons.
  8185. static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
  8186. ExprResult &LHS, ExprResult &RHS,
  8187. bool IsError) {
  8188. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
  8189. : diag::ext_typecheck_comparison_of_distinct_pointers)
  8190. << LHS.get()->getType() << RHS.get()->getType()
  8191. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8192. }
  8193. /// \brief Returns false if the pointers are converted to a composite type,
  8194. /// true otherwise.
  8195. static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
  8196. ExprResult &LHS, ExprResult &RHS) {
  8197. // C++ [expr.rel]p2:
  8198. // [...] Pointer conversions (4.10) and qualification
  8199. // conversions (4.4) are performed on pointer operands (or on
  8200. // a pointer operand and a null pointer constant) to bring
  8201. // them to their composite pointer type. [...]
  8202. //
  8203. // C++ [expr.eq]p1 uses the same notion for (in)equality
  8204. // comparisons of pointers.
  8205. QualType LHSType = LHS.get()->getType();
  8206. QualType RHSType = RHS.get()->getType();
  8207. assert(LHSType->isPointerType() || RHSType->isPointerType() ||
  8208. LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
  8209. QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
  8210. if (T.isNull()) {
  8211. if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
  8212. (RHSType->isPointerType() || RHSType->isMemberPointerType()))
  8213. diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
  8214. else
  8215. S.InvalidOperands(Loc, LHS, RHS);
  8216. return true;
  8217. }
  8218. LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
  8219. RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
  8220. return false;
  8221. }
  8222. static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
  8223. ExprResult &LHS,
  8224. ExprResult &RHS,
  8225. bool IsError) {
  8226. S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
  8227. : diag::ext_typecheck_comparison_of_fptr_to_void)
  8228. << LHS.get()->getType() << RHS.get()->getType()
  8229. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8230. }
  8231. static bool isObjCObjectLiteral(ExprResult &E) {
  8232. switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
  8233. case Stmt::ObjCArrayLiteralClass:
  8234. case Stmt::ObjCDictionaryLiteralClass:
  8235. case Stmt::ObjCStringLiteralClass:
  8236. case Stmt::ObjCBoxedExprClass:
  8237. return true;
  8238. default:
  8239. // Note that ObjCBoolLiteral is NOT an object literal!
  8240. return false;
  8241. }
  8242. }
  8243. static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
  8244. const ObjCObjectPointerType *Type =
  8245. LHS->getType()->getAs<ObjCObjectPointerType>();
  8246. // If this is not actually an Objective-C object, bail out.
  8247. if (!Type)
  8248. return false;
  8249. // Get the LHS object's interface type.
  8250. QualType InterfaceType = Type->getPointeeType();
  8251. // If the RHS isn't an Objective-C object, bail out.
  8252. if (!RHS->getType()->isObjCObjectPointerType())
  8253. return false;
  8254. // Try to find the -isEqual: method.
  8255. Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
  8256. ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
  8257. InterfaceType,
  8258. /*instance=*/true);
  8259. if (!Method) {
  8260. if (Type->isObjCIdType()) {
  8261. // For 'id', just check the global pool.
  8262. Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
  8263. /*receiverId=*/true);
  8264. } else {
  8265. // Check protocols.
  8266. Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
  8267. /*instance=*/true);
  8268. }
  8269. }
  8270. if (!Method)
  8271. return false;
  8272. QualType T = Method->parameters()[0]->getType();
  8273. if (!T->isObjCObjectPointerType())
  8274. return false;
  8275. QualType R = Method->getReturnType();
  8276. if (!R->isScalarType())
  8277. return false;
  8278. return true;
  8279. }
  8280. Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
  8281. FromE = FromE->IgnoreParenImpCasts();
  8282. switch (FromE->getStmtClass()) {
  8283. default:
  8284. break;
  8285. case Stmt::ObjCStringLiteralClass:
  8286. // "string literal"
  8287. return LK_String;
  8288. case Stmt::ObjCArrayLiteralClass:
  8289. // "array literal"
  8290. return LK_Array;
  8291. case Stmt::ObjCDictionaryLiteralClass:
  8292. // "dictionary literal"
  8293. return LK_Dictionary;
  8294. case Stmt::BlockExprClass:
  8295. return LK_Block;
  8296. case Stmt::ObjCBoxedExprClass: {
  8297. Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
  8298. switch (Inner->getStmtClass()) {
  8299. case Stmt::IntegerLiteralClass:
  8300. case Stmt::FloatingLiteralClass:
  8301. case Stmt::CharacterLiteralClass:
  8302. case Stmt::ObjCBoolLiteralExprClass:
  8303. case Stmt::CXXBoolLiteralExprClass:
  8304. // "numeric literal"
  8305. return LK_Numeric;
  8306. case Stmt::ImplicitCastExprClass: {
  8307. CastKind CK = cast<CastExpr>(Inner)->getCastKind();
  8308. // Boolean literals can be represented by implicit casts.
  8309. if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
  8310. return LK_Numeric;
  8311. break;
  8312. }
  8313. default:
  8314. break;
  8315. }
  8316. return LK_Boxed;
  8317. }
  8318. }
  8319. return LK_None;
  8320. }
  8321. static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
  8322. ExprResult &LHS, ExprResult &RHS,
  8323. BinaryOperator::Opcode Opc){
  8324. Expr *Literal;
  8325. Expr *Other;
  8326. if (isObjCObjectLiteral(LHS)) {
  8327. Literal = LHS.get();
  8328. Other = RHS.get();
  8329. } else {
  8330. Literal = RHS.get();
  8331. Other = LHS.get();
  8332. }
  8333. // Don't warn on comparisons against nil.
  8334. Other = Other->IgnoreParenCasts();
  8335. if (Other->isNullPointerConstant(S.getASTContext(),
  8336. Expr::NPC_ValueDependentIsNotNull))
  8337. return;
  8338. // This should be kept in sync with warn_objc_literal_comparison.
  8339. // LK_String should always be after the other literals, since it has its own
  8340. // warning flag.
  8341. Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
  8342. assert(LiteralKind != Sema::LK_Block);
  8343. if (LiteralKind == Sema::LK_None) {
  8344. llvm_unreachable("Unknown Objective-C object literal kind");
  8345. }
  8346. if (LiteralKind == Sema::LK_String)
  8347. S.Diag(Loc, diag::warn_objc_string_literal_comparison)
  8348. << Literal->getSourceRange();
  8349. else
  8350. S.Diag(Loc, diag::warn_objc_literal_comparison)
  8351. << LiteralKind << Literal->getSourceRange();
  8352. if (BinaryOperator::isEqualityOp(Opc) &&
  8353. hasIsEqualMethod(S, LHS.get(), RHS.get())) {
  8354. SourceLocation Start = LHS.get()->getLocStart();
  8355. SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
  8356. CharSourceRange OpRange =
  8357. CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
  8358. S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
  8359. << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
  8360. << FixItHint::CreateReplacement(OpRange, " isEqual:")
  8361. << FixItHint::CreateInsertion(End, "]");
  8362. }
  8363. }
  8364. /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
  8365. static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
  8366. ExprResult &RHS, SourceLocation Loc,
  8367. BinaryOperatorKind Opc) {
  8368. // Check that left hand side is !something.
  8369. UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
  8370. if (!UO || UO->getOpcode() != UO_LNot) return;
  8371. // Only check if the right hand side is non-bool arithmetic type.
  8372. if (RHS.get()->isKnownToHaveBooleanValue()) return;
  8373. // Make sure that the something in !something is not bool.
  8374. Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
  8375. if (SubExpr->isKnownToHaveBooleanValue()) return;
  8376. // Emit warning.
  8377. bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
  8378. S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
  8379. << Loc << IsBitwiseOp;
  8380. // First note suggest !(x < y)
  8381. SourceLocation FirstOpen = SubExpr->getLocStart();
  8382. SourceLocation FirstClose = RHS.get()->getLocEnd();
  8383. FirstClose = S.getLocForEndOfToken(FirstClose);
  8384. if (FirstClose.isInvalid())
  8385. FirstOpen = SourceLocation();
  8386. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
  8387. << IsBitwiseOp
  8388. << FixItHint::CreateInsertion(FirstOpen, "(")
  8389. << FixItHint::CreateInsertion(FirstClose, ")");
  8390. // Second note suggests (!x) < y
  8391. SourceLocation SecondOpen = LHS.get()->getLocStart();
  8392. SourceLocation SecondClose = LHS.get()->getLocEnd();
  8393. SecondClose = S.getLocForEndOfToken(SecondClose);
  8394. if (SecondClose.isInvalid())
  8395. SecondOpen = SourceLocation();
  8396. S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
  8397. << FixItHint::CreateInsertion(SecondOpen, "(")
  8398. << FixItHint::CreateInsertion(SecondClose, ")");
  8399. }
  8400. // Get the decl for a simple expression: a reference to a variable,
  8401. // an implicit C++ field reference, or an implicit ObjC ivar reference.
  8402. static ValueDecl *getCompareDecl(Expr *E) {
  8403. if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
  8404. return DR->getDecl();
  8405. if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
  8406. if (Ivar->isFreeIvar())
  8407. return Ivar->getDecl();
  8408. }
  8409. if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
  8410. if (Mem->isImplicitAccess())
  8411. return Mem->getMemberDecl();
  8412. }
  8413. return nullptr;
  8414. }
  8415. // C99 6.5.8, C++ [expr.rel]
  8416. QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
  8417. SourceLocation Loc, BinaryOperatorKind Opc,
  8418. bool IsRelational) {
  8419. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
  8420. // Handle vector comparisons separately.
  8421. if (LHS.get()->getType()->isVectorType() ||
  8422. RHS.get()->getType()->isVectorType())
  8423. return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
  8424. QualType LHSType = LHS.get()->getType();
  8425. QualType RHSType = RHS.get()->getType();
  8426. Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
  8427. Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
  8428. checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
  8429. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  8430. if (!LHSType->hasFloatingRepresentation() &&
  8431. !(LHSType->isBlockPointerType() && IsRelational) &&
  8432. !LHS.get()->getLocStart().isMacroID() &&
  8433. !RHS.get()->getLocStart().isMacroID() &&
  8434. !inTemplateInstantiation()) {
  8435. // For non-floating point types, check for self-comparisons of the form
  8436. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8437. // often indicate logic errors in the program.
  8438. //
  8439. // NOTE: Don't warn about comparison expressions resulting from macro
  8440. // expansion. Also don't warn about comparisons which are only self
  8441. // comparisons within a template specialization. The warnings should catch
  8442. // obvious cases in the definition of the template anyways. The idea is to
  8443. // warn when the typed comparison operator will always evaluate to the same
  8444. // result.
  8445. ValueDecl *DL = getCompareDecl(LHSStripped);
  8446. ValueDecl *DR = getCompareDecl(RHSStripped);
  8447. if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
  8448. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  8449. << 0 // self-
  8450. << (Opc == BO_EQ
  8451. || Opc == BO_LE
  8452. || Opc == BO_GE));
  8453. } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
  8454. !DL->getType()->isReferenceType() &&
  8455. !DR->getType()->isReferenceType()) {
  8456. // what is it always going to eval to?
  8457. char always_evals_to;
  8458. switch(Opc) {
  8459. case BO_EQ: // e.g. array1 == array2
  8460. always_evals_to = 0; // false
  8461. break;
  8462. case BO_NE: // e.g. array1 != array2
  8463. always_evals_to = 1; // true
  8464. break;
  8465. default:
  8466. // best we can say is 'a constant'
  8467. always_evals_to = 2; // e.g. array1 <= array2
  8468. break;
  8469. }
  8470. DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
  8471. << 1 // array
  8472. << always_evals_to);
  8473. }
  8474. if (isa<CastExpr>(LHSStripped))
  8475. LHSStripped = LHSStripped->IgnoreParenCasts();
  8476. if (isa<CastExpr>(RHSStripped))
  8477. RHSStripped = RHSStripped->IgnoreParenCasts();
  8478. // Warn about comparisons against a string constant (unless the other
  8479. // operand is null), the user probably wants strcmp.
  8480. Expr *literalString = nullptr;
  8481. Expr *literalStringStripped = nullptr;
  8482. if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
  8483. !RHSStripped->isNullPointerConstant(Context,
  8484. Expr::NPC_ValueDependentIsNull)) {
  8485. literalString = LHS.get();
  8486. literalStringStripped = LHSStripped;
  8487. } else if ((isa<StringLiteral>(RHSStripped) ||
  8488. isa<ObjCEncodeExpr>(RHSStripped)) &&
  8489. !LHSStripped->isNullPointerConstant(Context,
  8490. Expr::NPC_ValueDependentIsNull)) {
  8491. literalString = RHS.get();
  8492. literalStringStripped = RHSStripped;
  8493. }
  8494. if (literalString) {
  8495. DiagRuntimeBehavior(Loc, nullptr,
  8496. PDiag(diag::warn_stringcompare)
  8497. << isa<ObjCEncodeExpr>(literalStringStripped)
  8498. << literalString->getSourceRange());
  8499. }
  8500. }
  8501. // C99 6.5.8p3 / C99 6.5.9p4
  8502. UsualArithmeticConversions(LHS, RHS);
  8503. if (LHS.isInvalid() || RHS.isInvalid())
  8504. return QualType();
  8505. LHSType = LHS.get()->getType();
  8506. RHSType = RHS.get()->getType();
  8507. // The result of comparisons is 'bool' in C++, 'int' in C.
  8508. QualType ResultTy = Context.getLogicalOperationType();
  8509. if (IsRelational) {
  8510. if (LHSType->isRealType() && RHSType->isRealType())
  8511. return ResultTy;
  8512. } else {
  8513. // Check for comparisons of floating point operands using != and ==.
  8514. if (LHSType->hasFloatingRepresentation())
  8515. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  8516. if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
  8517. return ResultTy;
  8518. }
  8519. const Expr::NullPointerConstantKind LHSNullKind =
  8520. LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  8521. const Expr::NullPointerConstantKind RHSNullKind =
  8522. RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
  8523. bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
  8524. bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
  8525. if (!IsRelational && LHSIsNull != RHSIsNull) {
  8526. bool IsEquality = Opc == BO_EQ;
  8527. if (RHSIsNull)
  8528. DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
  8529. RHS.get()->getSourceRange());
  8530. else
  8531. DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
  8532. LHS.get()->getSourceRange());
  8533. }
  8534. if ((LHSType->isIntegerType() && !LHSIsNull) ||
  8535. (RHSType->isIntegerType() && !RHSIsNull)) {
  8536. // Skip normal pointer conversion checks in this case; we have better
  8537. // diagnostics for this below.
  8538. } else if (getLangOpts().CPlusPlus) {
  8539. // Equality comparison of a function pointer to a void pointer is invalid,
  8540. // but we allow it as an extension.
  8541. // FIXME: If we really want to allow this, should it be part of composite
  8542. // pointer type computation so it works in conditionals too?
  8543. if (!IsRelational &&
  8544. ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
  8545. (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
  8546. // This is a gcc extension compatibility comparison.
  8547. // In a SFINAE context, we treat this as a hard error to maintain
  8548. // conformance with the C++ standard.
  8549. diagnoseFunctionPointerToVoidComparison(
  8550. *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
  8551. if (isSFINAEContext())
  8552. return QualType();
  8553. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8554. return ResultTy;
  8555. }
  8556. // C++ [expr.eq]p2:
  8557. // If at least one operand is a pointer [...] bring them to their
  8558. // composite pointer type.
  8559. // C++ [expr.rel]p2:
  8560. // If both operands are pointers, [...] bring them to their composite
  8561. // pointer type.
  8562. if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
  8563. (IsRelational ? 2 : 1) &&
  8564. (!LangOpts.ObjCAutoRefCount ||
  8565. !(LHSType->isObjCObjectPointerType() ||
  8566. RHSType->isObjCObjectPointerType()))) {
  8567. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  8568. return QualType();
  8569. else
  8570. return ResultTy;
  8571. }
  8572. } else if (LHSType->isPointerType() &&
  8573. RHSType->isPointerType()) { // C99 6.5.8p2
  8574. // All of the following pointer-related warnings are GCC extensions, except
  8575. // when handling null pointer constants.
  8576. QualType LCanPointeeTy =
  8577. LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  8578. QualType RCanPointeeTy =
  8579. RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
  8580. // C99 6.5.9p2 and C99 6.5.8p2
  8581. if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
  8582. RCanPointeeTy.getUnqualifiedType())) {
  8583. // Valid unless a relational comparison of function pointers
  8584. if (IsRelational && LCanPointeeTy->isFunctionType()) {
  8585. Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
  8586. << LHSType << RHSType << LHS.get()->getSourceRange()
  8587. << RHS.get()->getSourceRange();
  8588. }
  8589. } else if (!IsRelational &&
  8590. (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
  8591. // Valid unless comparison between non-null pointer and function pointer
  8592. if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
  8593. && !LHSIsNull && !RHSIsNull)
  8594. diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
  8595. /*isError*/false);
  8596. } else {
  8597. // Invalid
  8598. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
  8599. }
  8600. if (LCanPointeeTy != RCanPointeeTy) {
  8601. // Treat NULL constant as a special case in OpenCL.
  8602. if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
  8603. const PointerType *LHSPtr = LHSType->getAs<PointerType>();
  8604. if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
  8605. Diag(Loc,
  8606. diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
  8607. << LHSType << RHSType << 0 /* comparison */
  8608. << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
  8609. }
  8610. }
  8611. LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
  8612. LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
  8613. CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
  8614. : CK_BitCast;
  8615. if (LHSIsNull && !RHSIsNull)
  8616. LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
  8617. else
  8618. RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
  8619. }
  8620. return ResultTy;
  8621. }
  8622. if (getLangOpts().CPlusPlus) {
  8623. // C++ [expr.eq]p4:
  8624. // Two operands of type std::nullptr_t or one operand of type
  8625. // std::nullptr_t and the other a null pointer constant compare equal.
  8626. if (!IsRelational && LHSIsNull && RHSIsNull) {
  8627. if (LHSType->isNullPtrType()) {
  8628. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8629. return ResultTy;
  8630. }
  8631. if (RHSType->isNullPtrType()) {
  8632. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8633. return ResultTy;
  8634. }
  8635. }
  8636. // Comparison of Objective-C pointers and block pointers against nullptr_t.
  8637. // These aren't covered by the composite pointer type rules.
  8638. if (!IsRelational && RHSType->isNullPtrType() &&
  8639. (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
  8640. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8641. return ResultTy;
  8642. }
  8643. if (!IsRelational && LHSType->isNullPtrType() &&
  8644. (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
  8645. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8646. return ResultTy;
  8647. }
  8648. if (IsRelational &&
  8649. ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
  8650. (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
  8651. // HACK: Relational comparison of nullptr_t against a pointer type is
  8652. // invalid per DR583, but we allow it within std::less<> and friends,
  8653. // since otherwise common uses of it break.
  8654. // FIXME: Consider removing this hack once LWG fixes std::less<> and
  8655. // friends to have std::nullptr_t overload candidates.
  8656. DeclContext *DC = CurContext;
  8657. if (isa<FunctionDecl>(DC))
  8658. DC = DC->getParent();
  8659. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  8660. if (CTSD->isInStdNamespace() &&
  8661. llvm::StringSwitch<bool>(CTSD->getName())
  8662. .Cases("less", "less_equal", "greater", "greater_equal", true)
  8663. .Default(false)) {
  8664. if (RHSType->isNullPtrType())
  8665. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8666. else
  8667. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8668. return ResultTy;
  8669. }
  8670. }
  8671. }
  8672. // C++ [expr.eq]p2:
  8673. // If at least one operand is a pointer to member, [...] bring them to
  8674. // their composite pointer type.
  8675. if (!IsRelational &&
  8676. (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
  8677. if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
  8678. return QualType();
  8679. else
  8680. return ResultTy;
  8681. }
  8682. // Handle scoped enumeration types specifically, since they don't promote
  8683. // to integers.
  8684. if (LHS.get()->getType()->isEnumeralType() &&
  8685. Context.hasSameUnqualifiedType(LHS.get()->getType(),
  8686. RHS.get()->getType()))
  8687. return ResultTy;
  8688. }
  8689. // Handle block pointer types.
  8690. if (!IsRelational && LHSType->isBlockPointerType() &&
  8691. RHSType->isBlockPointerType()) {
  8692. QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
  8693. QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
  8694. if (!LHSIsNull && !RHSIsNull &&
  8695. !Context.typesAreCompatible(lpointee, rpointee)) {
  8696. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  8697. << LHSType << RHSType << LHS.get()->getSourceRange()
  8698. << RHS.get()->getSourceRange();
  8699. }
  8700. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8701. return ResultTy;
  8702. }
  8703. // Allow block pointers to be compared with null pointer constants.
  8704. if (!IsRelational
  8705. && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
  8706. || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
  8707. if (!LHSIsNull && !RHSIsNull) {
  8708. if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
  8709. ->getPointeeType()->isVoidType())
  8710. || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
  8711. ->getPointeeType()->isVoidType())))
  8712. Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
  8713. << LHSType << RHSType << LHS.get()->getSourceRange()
  8714. << RHS.get()->getSourceRange();
  8715. }
  8716. if (LHSIsNull && !RHSIsNull)
  8717. LHS = ImpCastExprToType(LHS.get(), RHSType,
  8718. RHSType->isPointerType() ? CK_BitCast
  8719. : CK_AnyPointerToBlockPointerCast);
  8720. else
  8721. RHS = ImpCastExprToType(RHS.get(), LHSType,
  8722. LHSType->isPointerType() ? CK_BitCast
  8723. : CK_AnyPointerToBlockPointerCast);
  8724. return ResultTy;
  8725. }
  8726. if (LHSType->isObjCObjectPointerType() ||
  8727. RHSType->isObjCObjectPointerType()) {
  8728. const PointerType *LPT = LHSType->getAs<PointerType>();
  8729. const PointerType *RPT = RHSType->getAs<PointerType>();
  8730. if (LPT || RPT) {
  8731. bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
  8732. bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
  8733. if (!LPtrToVoid && !RPtrToVoid &&
  8734. !Context.typesAreCompatible(LHSType, RHSType)) {
  8735. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  8736. /*isError*/false);
  8737. }
  8738. if (LHSIsNull && !RHSIsNull) {
  8739. Expr *E = LHS.get();
  8740. if (getLangOpts().ObjCAutoRefCount)
  8741. CheckObjCConversion(SourceRange(), RHSType, E,
  8742. CCK_ImplicitConversion);
  8743. LHS = ImpCastExprToType(E, RHSType,
  8744. RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  8745. }
  8746. else {
  8747. Expr *E = RHS.get();
  8748. if (getLangOpts().ObjCAutoRefCount)
  8749. CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
  8750. /*Diagnose=*/true,
  8751. /*DiagnoseCFAudited=*/false, Opc);
  8752. RHS = ImpCastExprToType(E, LHSType,
  8753. LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
  8754. }
  8755. return ResultTy;
  8756. }
  8757. if (LHSType->isObjCObjectPointerType() &&
  8758. RHSType->isObjCObjectPointerType()) {
  8759. if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
  8760. diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
  8761. /*isError*/false);
  8762. if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
  8763. diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
  8764. if (LHSIsNull && !RHSIsNull)
  8765. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
  8766. else
  8767. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
  8768. return ResultTy;
  8769. }
  8770. }
  8771. if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
  8772. (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
  8773. unsigned DiagID = 0;
  8774. bool isError = false;
  8775. if (LangOpts.DebuggerSupport) {
  8776. // Under a debugger, allow the comparison of pointers to integers,
  8777. // since users tend to want to compare addresses.
  8778. } else if ((LHSIsNull && LHSType->isIntegerType()) ||
  8779. (RHSIsNull && RHSType->isIntegerType())) {
  8780. if (IsRelational) {
  8781. isError = getLangOpts().CPlusPlus;
  8782. DiagID =
  8783. isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
  8784. : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
  8785. }
  8786. } else if (getLangOpts().CPlusPlus) {
  8787. DiagID = diag::err_typecheck_comparison_of_pointer_integer;
  8788. isError = true;
  8789. } else if (IsRelational)
  8790. DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
  8791. else
  8792. DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
  8793. if (DiagID) {
  8794. Diag(Loc, DiagID)
  8795. << LHSType << RHSType << LHS.get()->getSourceRange()
  8796. << RHS.get()->getSourceRange();
  8797. if (isError)
  8798. return QualType();
  8799. }
  8800. if (LHSType->isIntegerType())
  8801. LHS = ImpCastExprToType(LHS.get(), RHSType,
  8802. LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  8803. else
  8804. RHS = ImpCastExprToType(RHS.get(), LHSType,
  8805. RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
  8806. return ResultTy;
  8807. }
  8808. // Handle block pointers.
  8809. if (!IsRelational && RHSIsNull
  8810. && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
  8811. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8812. return ResultTy;
  8813. }
  8814. if (!IsRelational && LHSIsNull
  8815. && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
  8816. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8817. return ResultTy;
  8818. }
  8819. if (getLangOpts().OpenCLVersion >= 200) {
  8820. if (LHSIsNull && RHSType->isQueueT()) {
  8821. LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
  8822. return ResultTy;
  8823. }
  8824. if (LHSType->isQueueT() && RHSIsNull) {
  8825. RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
  8826. return ResultTy;
  8827. }
  8828. }
  8829. return InvalidOperands(Loc, LHS, RHS);
  8830. }
  8831. // Return a signed ext_vector_type that is of identical size and number of
  8832. // elements. For floating point vectors, return an integer type of identical
  8833. // size and number of elements. In the non ext_vector_type case, search from
  8834. // the largest type to the smallest type to avoid cases where long long == long,
  8835. // where long gets picked over long long.
  8836. QualType Sema::GetSignedVectorType(QualType V) {
  8837. const VectorType *VTy = V->getAs<VectorType>();
  8838. unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
  8839. if (isa<ExtVectorType>(VTy)) {
  8840. if (TypeSize == Context.getTypeSize(Context.CharTy))
  8841. return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
  8842. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  8843. return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
  8844. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  8845. return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
  8846. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  8847. return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
  8848. assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
  8849. "Unhandled vector element size in vector compare");
  8850. return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
  8851. }
  8852. if (TypeSize == Context.getTypeSize(Context.LongLongTy))
  8853. return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
  8854. VectorType::GenericVector);
  8855. else if (TypeSize == Context.getTypeSize(Context.LongTy))
  8856. return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
  8857. VectorType::GenericVector);
  8858. else if (TypeSize == Context.getTypeSize(Context.IntTy))
  8859. return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
  8860. VectorType::GenericVector);
  8861. else if (TypeSize == Context.getTypeSize(Context.ShortTy))
  8862. return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
  8863. VectorType::GenericVector);
  8864. assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
  8865. "Unhandled vector element size in vector compare");
  8866. return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
  8867. VectorType::GenericVector);
  8868. }
  8869. /// CheckVectorCompareOperands - vector comparisons are a clang extension that
  8870. /// operates on extended vector types. Instead of producing an IntTy result,
  8871. /// like a scalar comparison, a vector comparison produces a vector of integer
  8872. /// types.
  8873. QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
  8874. SourceLocation Loc,
  8875. bool IsRelational) {
  8876. // Check to make sure we're operating on vectors of the same type and width,
  8877. // Allowing one side to be a scalar of element type.
  8878. QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
  8879. /*AllowBothBool*/true,
  8880. /*AllowBoolConversions*/getLangOpts().ZVector);
  8881. if (vType.isNull())
  8882. return vType;
  8883. QualType LHSType = LHS.get()->getType();
  8884. // If AltiVec, the comparison results in a numeric type, i.e.
  8885. // bool for C++, int for C
  8886. if (getLangOpts().AltiVec &&
  8887. vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
  8888. return Context.getLogicalOperationType();
  8889. // For non-floating point types, check for self-comparisons of the form
  8890. // x == x, x != x, x < x, etc. These always evaluate to a constant, and
  8891. // often indicate logic errors in the program.
  8892. if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
  8893. if (DeclRefExpr* DRL
  8894. = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
  8895. if (DeclRefExpr* DRR
  8896. = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
  8897. if (DRL->getDecl() == DRR->getDecl())
  8898. DiagRuntimeBehavior(Loc, nullptr,
  8899. PDiag(diag::warn_comparison_always)
  8900. << 0 // self-
  8901. << 2 // "a constant"
  8902. );
  8903. }
  8904. // Check for comparisons of floating point operands using != and ==.
  8905. if (!IsRelational && LHSType->hasFloatingRepresentation()) {
  8906. assert (RHS.get()->getType()->hasFloatingRepresentation());
  8907. CheckFloatComparison(Loc, LHS.get(), RHS.get());
  8908. }
  8909. // Return a signed type for the vector.
  8910. return GetSignedVectorType(vType);
  8911. }
  8912. QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  8913. SourceLocation Loc) {
  8914. // Ensure that either both operands are of the same vector type, or
  8915. // one operand is of a vector type and the other is of its element type.
  8916. QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
  8917. /*AllowBothBool*/true,
  8918. /*AllowBoolConversions*/false);
  8919. if (vType.isNull())
  8920. return InvalidOperands(Loc, LHS, RHS);
  8921. if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
  8922. vType->hasFloatingRepresentation())
  8923. return InvalidOperands(Loc, LHS, RHS);
  8924. // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
  8925. // usage of the logical operators && and || with vectors in C. This
  8926. // check could be notionally dropped.
  8927. if (!getLangOpts().CPlusPlus &&
  8928. !(isa<ExtVectorType>(vType->getAs<VectorType>())))
  8929. return InvalidLogicalVectorOperands(Loc, LHS, RHS);
  8930. return GetSignedVectorType(LHS.get()->getType());
  8931. }
  8932. inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
  8933. SourceLocation Loc,
  8934. BinaryOperatorKind Opc) {
  8935. checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
  8936. bool IsCompAssign =
  8937. Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
  8938. if (LHS.get()->getType()->isVectorType() ||
  8939. RHS.get()->getType()->isVectorType()) {
  8940. if (LHS.get()->getType()->hasIntegerRepresentation() &&
  8941. RHS.get()->getType()->hasIntegerRepresentation())
  8942. return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
  8943. /*AllowBothBool*/true,
  8944. /*AllowBoolConversions*/getLangOpts().ZVector);
  8945. return InvalidOperands(Loc, LHS, RHS);
  8946. }
  8947. if (Opc == BO_And)
  8948. diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
  8949. ExprResult LHSResult = LHS, RHSResult = RHS;
  8950. QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
  8951. IsCompAssign);
  8952. if (LHSResult.isInvalid() || RHSResult.isInvalid())
  8953. return QualType();
  8954. LHS = LHSResult.get();
  8955. RHS = RHSResult.get();
  8956. if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
  8957. return compType;
  8958. return InvalidOperands(Loc, LHS, RHS);
  8959. }
  8960. // C99 6.5.[13,14]
  8961. inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
  8962. SourceLocation Loc,
  8963. BinaryOperatorKind Opc) {
  8964. // Check vector operands differently.
  8965. if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
  8966. return CheckVectorLogicalOperands(LHS, RHS, Loc);
  8967. // Diagnose cases where the user write a logical and/or but probably meant a
  8968. // bitwise one. We do this when the LHS is a non-bool integer and the RHS
  8969. // is a constant.
  8970. if (LHS.get()->getType()->isIntegerType() &&
  8971. !LHS.get()->getType()->isBooleanType() &&
  8972. RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
  8973. // Don't warn in macros or template instantiations.
  8974. !Loc.isMacroID() && !inTemplateInstantiation()) {
  8975. // If the RHS can be constant folded, and if it constant folds to something
  8976. // that isn't 0 or 1 (which indicate a potential logical operation that
  8977. // happened to fold to true/false) then warn.
  8978. // Parens on the RHS are ignored.
  8979. llvm::APSInt Result;
  8980. if (RHS.get()->EvaluateAsInt(Result, Context))
  8981. if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
  8982. !RHS.get()->getExprLoc().isMacroID()) ||
  8983. (Result != 0 && Result != 1)) {
  8984. Diag(Loc, diag::warn_logical_instead_of_bitwise)
  8985. << RHS.get()->getSourceRange()
  8986. << (Opc == BO_LAnd ? "&&" : "||");
  8987. // Suggest replacing the logical operator with the bitwise version
  8988. Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
  8989. << (Opc == BO_LAnd ? "&" : "|")
  8990. << FixItHint::CreateReplacement(SourceRange(
  8991. Loc, getLocForEndOfToken(Loc)),
  8992. Opc == BO_LAnd ? "&" : "|");
  8993. if (Opc == BO_LAnd)
  8994. // Suggest replacing "Foo() && kNonZero" with "Foo()"
  8995. Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
  8996. << FixItHint::CreateRemoval(
  8997. SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
  8998. RHS.get()->getLocEnd()));
  8999. }
  9000. }
  9001. if (!Context.getLangOpts().CPlusPlus) {
  9002. // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
  9003. // not operate on the built-in scalar and vector float types.
  9004. if (Context.getLangOpts().OpenCL &&
  9005. Context.getLangOpts().OpenCLVersion < 120) {
  9006. if (LHS.get()->getType()->isFloatingType() ||
  9007. RHS.get()->getType()->isFloatingType())
  9008. return InvalidOperands(Loc, LHS, RHS);
  9009. }
  9010. LHS = UsualUnaryConversions(LHS.get());
  9011. if (LHS.isInvalid())
  9012. return QualType();
  9013. RHS = UsualUnaryConversions(RHS.get());
  9014. if (RHS.isInvalid())
  9015. return QualType();
  9016. if (!LHS.get()->getType()->isScalarType() ||
  9017. !RHS.get()->getType()->isScalarType())
  9018. return InvalidOperands(Loc, LHS, RHS);
  9019. return Context.IntTy;
  9020. }
  9021. // The following is safe because we only use this method for
  9022. // non-overloadable operands.
  9023. // C++ [expr.log.and]p1
  9024. // C++ [expr.log.or]p1
  9025. // The operands are both contextually converted to type bool.
  9026. ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
  9027. if (LHSRes.isInvalid())
  9028. return InvalidOperands(Loc, LHS, RHS);
  9029. LHS = LHSRes;
  9030. ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
  9031. if (RHSRes.isInvalid())
  9032. return InvalidOperands(Loc, LHS, RHS);
  9033. RHS = RHSRes;
  9034. // C++ [expr.log.and]p2
  9035. // C++ [expr.log.or]p2
  9036. // The result is a bool.
  9037. return Context.BoolTy;
  9038. }
  9039. static bool IsReadonlyMessage(Expr *E, Sema &S) {
  9040. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  9041. if (!ME) return false;
  9042. if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
  9043. ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
  9044. ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
  9045. if (!Base) return false;
  9046. return Base->getMethodDecl() != nullptr;
  9047. }
  9048. /// Is the given expression (which must be 'const') a reference to a
  9049. /// variable which was originally non-const, but which has become
  9050. /// 'const' due to being captured within a block?
  9051. enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
  9052. static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
  9053. assert(E->isLValue() && E->getType().isConstQualified());
  9054. E = E->IgnoreParens();
  9055. // Must be a reference to a declaration from an enclosing scope.
  9056. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  9057. if (!DRE) return NCCK_None;
  9058. if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
  9059. // The declaration must be a variable which is not declared 'const'.
  9060. VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
  9061. if (!var) return NCCK_None;
  9062. if (var->getType().isConstQualified()) return NCCK_None;
  9063. assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
  9064. // Decide whether the first capture was for a block or a lambda.
  9065. DeclContext *DC = S.CurContext, *Prev = nullptr;
  9066. // Decide whether the first capture was for a block or a lambda.
  9067. while (DC) {
  9068. // For init-capture, it is possible that the variable belongs to the
  9069. // template pattern of the current context.
  9070. if (auto *FD = dyn_cast<FunctionDecl>(DC))
  9071. if (var->isInitCapture() &&
  9072. FD->getTemplateInstantiationPattern() == var->getDeclContext())
  9073. break;
  9074. if (DC == var->getDeclContext())
  9075. break;
  9076. Prev = DC;
  9077. DC = DC->getParent();
  9078. }
  9079. // Unless we have an init-capture, we've gone one step too far.
  9080. if (!var->isInitCapture())
  9081. DC = Prev;
  9082. return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
  9083. }
  9084. static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
  9085. Ty = Ty.getNonReferenceType();
  9086. if (IsDereference && Ty->isPointerType())
  9087. Ty = Ty->getPointeeType();
  9088. return !Ty.isConstQualified();
  9089. }
  9090. // Update err_typecheck_assign_const and note_typecheck_assign_const
  9091. // when this enum is changed.
  9092. enum {
  9093. ConstFunction,
  9094. ConstVariable,
  9095. ConstMember,
  9096. ConstMethod,
  9097. NestedConstMember,
  9098. ConstUnknown, // Keep as last element
  9099. };
  9100. /// Emit the "read-only variable not assignable" error and print notes to give
  9101. /// more information about why the variable is not assignable, such as pointing
  9102. /// to the declaration of a const variable, showing that a method is const, or
  9103. /// that the function is returning a const reference.
  9104. static void DiagnoseConstAssignment(Sema &S, const Expr *E,
  9105. SourceLocation Loc) {
  9106. SourceRange ExprRange = E->getSourceRange();
  9107. // Only emit one error on the first const found. All other consts will emit
  9108. // a note to the error.
  9109. bool DiagnosticEmitted = false;
  9110. // Track if the current expression is the result of a dereference, and if the
  9111. // next checked expression is the result of a dereference.
  9112. bool IsDereference = false;
  9113. bool NextIsDereference = false;
  9114. // Loop to process MemberExpr chains.
  9115. while (true) {
  9116. IsDereference = NextIsDereference;
  9117. E = E->IgnoreImplicit()->IgnoreParenImpCasts();
  9118. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  9119. NextIsDereference = ME->isArrow();
  9120. const ValueDecl *VD = ME->getMemberDecl();
  9121. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  9122. // Mutable fields can be modified even if the class is const.
  9123. if (Field->isMutable()) {
  9124. assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
  9125. break;
  9126. }
  9127. if (!IsTypeModifiable(Field->getType(), IsDereference)) {
  9128. if (!DiagnosticEmitted) {
  9129. S.Diag(Loc, diag::err_typecheck_assign_const)
  9130. << ExprRange << ConstMember << false /*static*/ << Field
  9131. << Field->getType();
  9132. DiagnosticEmitted = true;
  9133. }
  9134. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9135. << ConstMember << false /*static*/ << Field << Field->getType()
  9136. << Field->getSourceRange();
  9137. }
  9138. E = ME->getBase();
  9139. continue;
  9140. } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
  9141. if (VDecl->getType().isConstQualified()) {
  9142. if (!DiagnosticEmitted) {
  9143. S.Diag(Loc, diag::err_typecheck_assign_const)
  9144. << ExprRange << ConstMember << true /*static*/ << VDecl
  9145. << VDecl->getType();
  9146. DiagnosticEmitted = true;
  9147. }
  9148. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9149. << ConstMember << true /*static*/ << VDecl << VDecl->getType()
  9150. << VDecl->getSourceRange();
  9151. }
  9152. // Static fields do not inherit constness from parents.
  9153. break;
  9154. }
  9155. break;
  9156. } // End MemberExpr
  9157. break;
  9158. }
  9159. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  9160. // Function calls
  9161. const FunctionDecl *FD = CE->getDirectCallee();
  9162. if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
  9163. if (!DiagnosticEmitted) {
  9164. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9165. << ConstFunction << FD;
  9166. DiagnosticEmitted = true;
  9167. }
  9168. S.Diag(FD->getReturnTypeSourceRange().getBegin(),
  9169. diag::note_typecheck_assign_const)
  9170. << ConstFunction << FD << FD->getReturnType()
  9171. << FD->getReturnTypeSourceRange();
  9172. }
  9173. } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  9174. // Point to variable declaration.
  9175. if (const ValueDecl *VD = DRE->getDecl()) {
  9176. if (!IsTypeModifiable(VD->getType(), IsDereference)) {
  9177. if (!DiagnosticEmitted) {
  9178. S.Diag(Loc, diag::err_typecheck_assign_const)
  9179. << ExprRange << ConstVariable << VD << VD->getType();
  9180. DiagnosticEmitted = true;
  9181. }
  9182. S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
  9183. << ConstVariable << VD << VD->getType() << VD->getSourceRange();
  9184. }
  9185. }
  9186. } else if (isa<CXXThisExpr>(E)) {
  9187. if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
  9188. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
  9189. if (MD->isConst()) {
  9190. if (!DiagnosticEmitted) {
  9191. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
  9192. << ConstMethod << MD;
  9193. DiagnosticEmitted = true;
  9194. }
  9195. S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
  9196. << ConstMethod << MD << MD->getSourceRange();
  9197. }
  9198. }
  9199. }
  9200. }
  9201. if (DiagnosticEmitted)
  9202. return;
  9203. // Can't determine a more specific message, so display the generic error.
  9204. S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
  9205. }
  9206. enum OriginalExprKind {
  9207. OEK_Variable,
  9208. OEK_Member,
  9209. OEK_LValue
  9210. };
  9211. static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
  9212. const RecordType *Ty,
  9213. SourceLocation Loc, SourceRange Range,
  9214. OriginalExprKind OEK,
  9215. bool &DiagnosticEmitted,
  9216. bool IsNested = false) {
  9217. // We walk the record hierarchy breadth-first to ensure that we print
  9218. // diagnostics in field nesting order.
  9219. // First, check every field for constness.
  9220. for (const FieldDecl *Field : Ty->getDecl()->fields()) {
  9221. if (Field->getType().isConstQualified()) {
  9222. if (!DiagnosticEmitted) {
  9223. S.Diag(Loc, diag::err_typecheck_assign_const)
  9224. << Range << NestedConstMember << OEK << VD
  9225. << IsNested << Field;
  9226. DiagnosticEmitted = true;
  9227. }
  9228. S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
  9229. << NestedConstMember << IsNested << Field
  9230. << Field->getType() << Field->getSourceRange();
  9231. }
  9232. }
  9233. // Then, recurse.
  9234. for (const FieldDecl *Field : Ty->getDecl()->fields()) {
  9235. QualType FTy = Field->getType();
  9236. if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
  9237. DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
  9238. OEK, DiagnosticEmitted, true);
  9239. }
  9240. }
  9241. /// Emit an error for the case where a record we are trying to assign to has a
  9242. /// const-qualified field somewhere in its hierarchy.
  9243. static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
  9244. SourceLocation Loc) {
  9245. QualType Ty = E->getType();
  9246. assert(Ty->isRecordType() && "lvalue was not record?");
  9247. SourceRange Range = E->getSourceRange();
  9248. const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
  9249. bool DiagEmitted = false;
  9250. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  9251. DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
  9252. Range, OEK_Member, DiagEmitted);
  9253. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  9254. DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
  9255. Range, OEK_Variable, DiagEmitted);
  9256. else
  9257. DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
  9258. Range, OEK_LValue, DiagEmitted);
  9259. if (!DiagEmitted)
  9260. DiagnoseConstAssignment(S, E, Loc);
  9261. }
  9262. /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
  9263. /// emit an error and return true. If so, return false.
  9264. static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
  9265. assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
  9266. S.CheckShadowingDeclModification(E, Loc);
  9267. SourceLocation OrigLoc = Loc;
  9268. Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
  9269. &Loc);
  9270. if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
  9271. IsLV = Expr::MLV_InvalidMessageExpression;
  9272. if (IsLV == Expr::MLV_Valid)
  9273. return false;
  9274. unsigned DiagID = 0;
  9275. bool NeedType = false;
  9276. switch (IsLV) { // C99 6.5.16p2
  9277. case Expr::MLV_ConstQualified:
  9278. // Use a specialized diagnostic when we're assigning to an object
  9279. // from an enclosing function or block.
  9280. if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
  9281. if (NCCK == NCCK_Block)
  9282. DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
  9283. else
  9284. DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
  9285. break;
  9286. }
  9287. // In ARC, use some specialized diagnostics for occasions where we
  9288. // infer 'const'. These are always pseudo-strong variables.
  9289. if (S.getLangOpts().ObjCAutoRefCount) {
  9290. DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
  9291. if (declRef && isa<VarDecl>(declRef->getDecl())) {
  9292. VarDecl *var = cast<VarDecl>(declRef->getDecl());
  9293. // Use the normal diagnostic if it's pseudo-__strong but the
  9294. // user actually wrote 'const'.
  9295. if (var->isARCPseudoStrong() &&
  9296. (!var->getTypeSourceInfo() ||
  9297. !var->getTypeSourceInfo()->getType().isConstQualified())) {
  9298. // There are two pseudo-strong cases:
  9299. // - self
  9300. ObjCMethodDecl *method = S.getCurMethodDecl();
  9301. if (method && var == method->getSelfDecl())
  9302. DiagID = method->isClassMethod()
  9303. ? diag::err_typecheck_arc_assign_self_class_method
  9304. : diag::err_typecheck_arc_assign_self;
  9305. // - fast enumeration variables
  9306. else
  9307. DiagID = diag::err_typecheck_arr_assign_enumeration;
  9308. SourceRange Assign;
  9309. if (Loc != OrigLoc)
  9310. Assign = SourceRange(OrigLoc, OrigLoc);
  9311. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9312. // We need to preserve the AST regardless, so migration tool
  9313. // can do its job.
  9314. return false;
  9315. }
  9316. }
  9317. }
  9318. // If none of the special cases above are triggered, then this is a
  9319. // simple const assignment.
  9320. if (DiagID == 0) {
  9321. DiagnoseConstAssignment(S, E, Loc);
  9322. return true;
  9323. }
  9324. break;
  9325. case Expr::MLV_ConstAddrSpace:
  9326. DiagnoseConstAssignment(S, E, Loc);
  9327. return true;
  9328. case Expr::MLV_ConstQualifiedField:
  9329. DiagnoseRecursiveConstFields(S, E, Loc);
  9330. return true;
  9331. case Expr::MLV_ArrayType:
  9332. case Expr::MLV_ArrayTemporary:
  9333. DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
  9334. NeedType = true;
  9335. break;
  9336. case Expr::MLV_NotObjectType:
  9337. DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
  9338. NeedType = true;
  9339. break;
  9340. case Expr::MLV_LValueCast:
  9341. DiagID = diag::err_typecheck_lvalue_casts_not_supported;
  9342. break;
  9343. case Expr::MLV_Valid:
  9344. llvm_unreachable("did not take early return for MLV_Valid");
  9345. case Expr::MLV_InvalidExpression:
  9346. case Expr::MLV_MemberFunction:
  9347. case Expr::MLV_ClassTemporary:
  9348. DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
  9349. break;
  9350. case Expr::MLV_IncompleteType:
  9351. case Expr::MLV_IncompleteVoidType:
  9352. return S.RequireCompleteType(Loc, E->getType(),
  9353. diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
  9354. case Expr::MLV_DuplicateVectorComponents:
  9355. DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
  9356. break;
  9357. case Expr::MLV_NoSetterProperty:
  9358. llvm_unreachable("readonly properties should be processed differently");
  9359. case Expr::MLV_InvalidMessageExpression:
  9360. DiagID = diag::err_readonly_message_assignment;
  9361. break;
  9362. case Expr::MLV_SubObjCPropertySetting:
  9363. DiagID = diag::err_no_subobject_property_setting;
  9364. break;
  9365. }
  9366. SourceRange Assign;
  9367. if (Loc != OrigLoc)
  9368. Assign = SourceRange(OrigLoc, OrigLoc);
  9369. if (NeedType)
  9370. S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
  9371. else
  9372. S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
  9373. return true;
  9374. }
  9375. static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
  9376. SourceLocation Loc,
  9377. Sema &Sema) {
  9378. // C / C++ fields
  9379. MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
  9380. MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
  9381. if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
  9382. if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
  9383. Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
  9384. }
  9385. // Objective-C instance variables
  9386. ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
  9387. ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
  9388. if (OL && OR && OL->getDecl() == OR->getDecl()) {
  9389. DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
  9390. DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
  9391. if (RL && RR && RL->getDecl() == RR->getDecl())
  9392. Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
  9393. }
  9394. }
  9395. // C99 6.5.16.1
  9396. QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
  9397. SourceLocation Loc,
  9398. QualType CompoundType) {
  9399. assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
  9400. // Verify that LHS is a modifiable lvalue, and emit error if not.
  9401. if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
  9402. return QualType();
  9403. QualType LHSType = LHSExpr->getType();
  9404. QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
  9405. CompoundType;
  9406. // OpenCL v1.2 s6.1.1.1 p2:
  9407. // The half data type can only be used to declare a pointer to a buffer that
  9408. // contains half values
  9409. if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
  9410. LHSType->isHalfType()) {
  9411. Diag(Loc, diag::err_opencl_half_load_store) << 1
  9412. << LHSType.getUnqualifiedType();
  9413. return QualType();
  9414. }
  9415. AssignConvertType ConvTy;
  9416. if (CompoundType.isNull()) {
  9417. Expr *RHSCheck = RHS.get();
  9418. CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
  9419. QualType LHSTy(LHSType);
  9420. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  9421. if (RHS.isInvalid())
  9422. return QualType();
  9423. // Special case of NSObject attributes on c-style pointer types.
  9424. if (ConvTy == IncompatiblePointer &&
  9425. ((Context.isObjCNSObjectType(LHSType) &&
  9426. RHSType->isObjCObjectPointerType()) ||
  9427. (Context.isObjCNSObjectType(RHSType) &&
  9428. LHSType->isObjCObjectPointerType())))
  9429. ConvTy = Compatible;
  9430. if (ConvTy == Compatible &&
  9431. LHSType->isObjCObjectType())
  9432. Diag(Loc, diag::err_objc_object_assignment)
  9433. << LHSType;
  9434. // If the RHS is a unary plus or minus, check to see if they = and + are
  9435. // right next to each other. If so, the user may have typo'd "x =+ 4"
  9436. // instead of "x += 4".
  9437. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
  9438. RHSCheck = ICE->getSubExpr();
  9439. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
  9440. if ((UO->getOpcode() == UO_Plus ||
  9441. UO->getOpcode() == UO_Minus) &&
  9442. Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
  9443. // Only if the two operators are exactly adjacent.
  9444. Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
  9445. // And there is a space or other character before the subexpr of the
  9446. // unary +/-. We don't want to warn on "x=-1".
  9447. Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
  9448. UO->getSubExpr()->getLocStart().isFileID()) {
  9449. Diag(Loc, diag::warn_not_compound_assign)
  9450. << (UO->getOpcode() == UO_Plus ? "+" : "-")
  9451. << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
  9452. }
  9453. }
  9454. if (ConvTy == Compatible) {
  9455. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
  9456. // Warn about retain cycles where a block captures the LHS, but
  9457. // not if the LHS is a simple variable into which the block is
  9458. // being stored...unless that variable can be captured by reference!
  9459. const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
  9460. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
  9461. if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
  9462. checkRetainCycles(LHSExpr, RHS.get());
  9463. }
  9464. if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  9465. LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
  9466. // It is safe to assign a weak reference into a strong variable.
  9467. // Although this code can still have problems:
  9468. // id x = self.weakProp;
  9469. // id y = self.weakProp;
  9470. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9471. // paths through the function. This should be revisited if
  9472. // -Wrepeated-use-of-weak is made flow-sensitive.
  9473. // For ObjCWeak only, we do not warn if the assign is to a non-weak
  9474. // variable, which will be valid for the current autorelease scope.
  9475. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9476. RHS.get()->getLocStart()))
  9477. getCurFunction()->markSafeWeakUse(RHS.get());
  9478. } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
  9479. checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
  9480. }
  9481. }
  9482. } else {
  9483. // Compound assignment "x += y"
  9484. ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
  9485. }
  9486. if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
  9487. RHS.get(), AA_Assigning))
  9488. return QualType();
  9489. CheckForNullPointerDereference(*this, LHSExpr);
  9490. // C99 6.5.16p3: The type of an assignment expression is the type of the
  9491. // left operand unless the left operand has qualified type, in which case
  9492. // it is the unqualified version of the type of the left operand.
  9493. // C99 6.5.16.1p2: In simple assignment, the value of the right operand
  9494. // is converted to the type of the assignment expression (above).
  9495. // C++ 5.17p1: the type of the assignment expression is that of its left
  9496. // operand.
  9497. return (getLangOpts().CPlusPlus
  9498. ? LHSType : LHSType.getUnqualifiedType());
  9499. }
  9500. // Only ignore explicit casts to void.
  9501. static bool IgnoreCommaOperand(const Expr *E) {
  9502. E = E->IgnoreParens();
  9503. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  9504. if (CE->getCastKind() == CK_ToVoid) {
  9505. return true;
  9506. }
  9507. }
  9508. return false;
  9509. }
  9510. // Look for instances where it is likely the comma operator is confused with
  9511. // another operator. There is a whitelist of acceptable expressions for the
  9512. // left hand side of the comma operator, otherwise emit a warning.
  9513. void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
  9514. // No warnings in macros
  9515. if (Loc.isMacroID())
  9516. return;
  9517. // Don't warn in template instantiations.
  9518. if (inTemplateInstantiation())
  9519. return;
  9520. // Scope isn't fine-grained enough to whitelist the specific cases, so
  9521. // instead, skip more than needed, then call back into here with the
  9522. // CommaVisitor in SemaStmt.cpp.
  9523. // The whitelisted locations are the initialization and increment portions
  9524. // of a for loop. The additional checks are on the condition of
  9525. // if statements, do/while loops, and for loops.
  9526. const unsigned ForIncrementFlags =
  9527. Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
  9528. const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
  9529. const unsigned ScopeFlags = getCurScope()->getFlags();
  9530. if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
  9531. (ScopeFlags & ForInitFlags) == ForInitFlags)
  9532. return;
  9533. // If there are multiple comma operators used together, get the RHS of the
  9534. // of the comma operator as the LHS.
  9535. while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
  9536. if (BO->getOpcode() != BO_Comma)
  9537. break;
  9538. LHS = BO->getRHS();
  9539. }
  9540. // Only allow some expressions on LHS to not warn.
  9541. if (IgnoreCommaOperand(LHS))
  9542. return;
  9543. Diag(Loc, diag::warn_comma_operator);
  9544. Diag(LHS->getLocStart(), diag::note_cast_to_void)
  9545. << LHS->getSourceRange()
  9546. << FixItHint::CreateInsertion(LHS->getLocStart(),
  9547. LangOpts.CPlusPlus ? "static_cast<void>("
  9548. : "(void)(")
  9549. << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
  9550. ")");
  9551. }
  9552. // C99 6.5.17
  9553. static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
  9554. SourceLocation Loc) {
  9555. LHS = S.CheckPlaceholderExpr(LHS.get());
  9556. RHS = S.CheckPlaceholderExpr(RHS.get());
  9557. if (LHS.isInvalid() || RHS.isInvalid())
  9558. return QualType();
  9559. // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
  9560. // operands, but not unary promotions.
  9561. // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
  9562. // So we treat the LHS as a ignored value, and in C++ we allow the
  9563. // containing site to determine what should be done with the RHS.
  9564. LHS = S.IgnoredValueConversions(LHS.get());
  9565. if (LHS.isInvalid())
  9566. return QualType();
  9567. S.DiagnoseUnusedExprResult(LHS.get());
  9568. if (!S.getLangOpts().CPlusPlus) {
  9569. RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
  9570. if (RHS.isInvalid())
  9571. return QualType();
  9572. if (!RHS.get()->getType()->isVoidType())
  9573. S.RequireCompleteType(Loc, RHS.get()->getType(),
  9574. diag::err_incomplete_type);
  9575. }
  9576. if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
  9577. S.DiagnoseCommaOperator(LHS.get(), Loc);
  9578. return RHS.get()->getType();
  9579. }
  9580. /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
  9581. /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
  9582. static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
  9583. ExprValueKind &VK,
  9584. ExprObjectKind &OK,
  9585. SourceLocation OpLoc,
  9586. bool IsInc, bool IsPrefix) {
  9587. if (Op->isTypeDependent())
  9588. return S.Context.DependentTy;
  9589. QualType ResType = Op->getType();
  9590. // Atomic types can be used for increment / decrement where the non-atomic
  9591. // versions can, so ignore the _Atomic() specifier for the purpose of
  9592. // checking.
  9593. if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
  9594. ResType = ResAtomicType->getValueType();
  9595. assert(!ResType.isNull() && "no type for increment/decrement expression");
  9596. if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
  9597. // Decrement of bool is not allowed.
  9598. if (!IsInc) {
  9599. S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
  9600. return QualType();
  9601. }
  9602. // Increment of bool sets it to true, but is deprecated.
  9603. S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
  9604. : diag::warn_increment_bool)
  9605. << Op->getSourceRange();
  9606. } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
  9607. // Error on enum increments and decrements in C++ mode
  9608. S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
  9609. return QualType();
  9610. } else if (ResType->isRealType()) {
  9611. // OK!
  9612. } else if (ResType->isPointerType()) {
  9613. // C99 6.5.2.4p2, 6.5.6p2
  9614. if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
  9615. return QualType();
  9616. } else if (ResType->isObjCObjectPointerType()) {
  9617. // On modern runtimes, ObjC pointer arithmetic is forbidden.
  9618. // Otherwise, we just need a complete type.
  9619. if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
  9620. checkArithmeticOnObjCPointer(S, OpLoc, Op))
  9621. return QualType();
  9622. } else if (ResType->isAnyComplexType()) {
  9623. // C99 does not support ++/-- on complex types, we allow as an extension.
  9624. S.Diag(OpLoc, diag::ext_integer_increment_complex)
  9625. << ResType << Op->getSourceRange();
  9626. } else if (ResType->isPlaceholderType()) {
  9627. ExprResult PR = S.CheckPlaceholderExpr(Op);
  9628. if (PR.isInvalid()) return QualType();
  9629. return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
  9630. IsInc, IsPrefix);
  9631. } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
  9632. // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
  9633. } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
  9634. (ResType->getAs<VectorType>()->getVectorKind() !=
  9635. VectorType::AltiVecBool)) {
  9636. // The z vector extensions allow ++ and -- for non-bool vectors.
  9637. } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
  9638. ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
  9639. // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
  9640. } else {
  9641. S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
  9642. << ResType << int(IsInc) << Op->getSourceRange();
  9643. return QualType();
  9644. }
  9645. // At this point, we know we have a real, complex or pointer type.
  9646. // Now make sure the operand is a modifiable lvalue.
  9647. if (CheckForModifiableLvalue(Op, OpLoc, S))
  9648. return QualType();
  9649. // In C++, a prefix increment is the same type as the operand. Otherwise
  9650. // (in C or with postfix), the increment is the unqualified type of the
  9651. // operand.
  9652. if (IsPrefix && S.getLangOpts().CPlusPlus) {
  9653. VK = VK_LValue;
  9654. OK = Op->getObjectKind();
  9655. return ResType;
  9656. } else {
  9657. VK = VK_RValue;
  9658. return ResType.getUnqualifiedType();
  9659. }
  9660. }
  9661. /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
  9662. /// This routine allows us to typecheck complex/recursive expressions
  9663. /// where the declaration is needed for type checking. We only need to
  9664. /// handle cases when the expression references a function designator
  9665. /// or is an lvalue. Here are some examples:
  9666. /// - &(x) => x
  9667. /// - &*****f => f for f a function designator.
  9668. /// - &s.xx => s
  9669. /// - &s.zz[1].yy -> s, if zz is an array
  9670. /// - *(x + 1) -> x, if x is an array
  9671. /// - &"123"[2] -> 0
  9672. /// - & __real__ x -> x
  9673. static ValueDecl *getPrimaryDecl(Expr *E) {
  9674. switch (E->getStmtClass()) {
  9675. case Stmt::DeclRefExprClass:
  9676. return cast<DeclRefExpr>(E)->getDecl();
  9677. case Stmt::MemberExprClass:
  9678. // If this is an arrow operator, the address is an offset from
  9679. // the base's value, so the object the base refers to is
  9680. // irrelevant.
  9681. if (cast<MemberExpr>(E)->isArrow())
  9682. return nullptr;
  9683. // Otherwise, the expression refers to a part of the base
  9684. return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
  9685. case Stmt::ArraySubscriptExprClass: {
  9686. // FIXME: This code shouldn't be necessary! We should catch the implicit
  9687. // promotion of register arrays earlier.
  9688. Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
  9689. if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
  9690. if (ICE->getSubExpr()->getType()->isArrayType())
  9691. return getPrimaryDecl(ICE->getSubExpr());
  9692. }
  9693. return nullptr;
  9694. }
  9695. case Stmt::UnaryOperatorClass: {
  9696. UnaryOperator *UO = cast<UnaryOperator>(E);
  9697. switch(UO->getOpcode()) {
  9698. case UO_Real:
  9699. case UO_Imag:
  9700. case UO_Extension:
  9701. return getPrimaryDecl(UO->getSubExpr());
  9702. default:
  9703. return nullptr;
  9704. }
  9705. }
  9706. case Stmt::ParenExprClass:
  9707. return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
  9708. case Stmt::ImplicitCastExprClass:
  9709. // If the result of an implicit cast is an l-value, we care about
  9710. // the sub-expression; otherwise, the result here doesn't matter.
  9711. return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
  9712. default:
  9713. return nullptr;
  9714. }
  9715. }
  9716. namespace {
  9717. enum {
  9718. AO_Bit_Field = 0,
  9719. AO_Vector_Element = 1,
  9720. AO_Property_Expansion = 2,
  9721. AO_Register_Variable = 3,
  9722. AO_No_Error = 4
  9723. };
  9724. }
  9725. /// \brief Diagnose invalid operand for address of operations.
  9726. ///
  9727. /// \param Type The type of operand which cannot have its address taken.
  9728. static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
  9729. Expr *E, unsigned Type) {
  9730. S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
  9731. }
  9732. /// CheckAddressOfOperand - The operand of & must be either a function
  9733. /// designator or an lvalue designating an object. If it is an lvalue, the
  9734. /// object cannot be declared with storage class register or be a bit field.
  9735. /// Note: The usual conversions are *not* applied to the operand of the &
  9736. /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
  9737. /// In C++, the operand might be an overloaded function name, in which case
  9738. /// we allow the '&' but retain the overloaded-function type.
  9739. QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
  9740. if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
  9741. if (PTy->getKind() == BuiltinType::Overload) {
  9742. Expr *E = OrigOp.get()->IgnoreParens();
  9743. if (!isa<OverloadExpr>(E)) {
  9744. assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
  9745. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
  9746. << OrigOp.get()->getSourceRange();
  9747. return QualType();
  9748. }
  9749. OverloadExpr *Ovl = cast<OverloadExpr>(E);
  9750. if (isa<UnresolvedMemberExpr>(Ovl))
  9751. if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
  9752. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  9753. << OrigOp.get()->getSourceRange();
  9754. return QualType();
  9755. }
  9756. return Context.OverloadTy;
  9757. }
  9758. if (PTy->getKind() == BuiltinType::UnknownAny)
  9759. return Context.UnknownAnyTy;
  9760. if (PTy->getKind() == BuiltinType::BoundMember) {
  9761. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  9762. << OrigOp.get()->getSourceRange();
  9763. return QualType();
  9764. }
  9765. OrigOp = CheckPlaceholderExpr(OrigOp.get());
  9766. if (OrigOp.isInvalid()) return QualType();
  9767. }
  9768. if (OrigOp.get()->isTypeDependent())
  9769. return Context.DependentTy;
  9770. assert(!OrigOp.get()->getType()->isPlaceholderType());
  9771. // Make sure to ignore parentheses in subsequent checks
  9772. Expr *op = OrigOp.get()->IgnoreParens();
  9773. // In OpenCL captures for blocks called as lambda functions
  9774. // are located in the private address space. Blocks used in
  9775. // enqueue_kernel can be located in a different address space
  9776. // depending on a vendor implementation. Thus preventing
  9777. // taking an address of the capture to avoid invalid AS casts.
  9778. if (LangOpts.OpenCL) {
  9779. auto* VarRef = dyn_cast<DeclRefExpr>(op);
  9780. if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
  9781. Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
  9782. return QualType();
  9783. }
  9784. }
  9785. if (getLangOpts().C99) {
  9786. // Implement C99-only parts of addressof rules.
  9787. if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
  9788. if (uOp->getOpcode() == UO_Deref)
  9789. // Per C99 6.5.3.2, the address of a deref always returns a valid result
  9790. // (assuming the deref expression is valid).
  9791. return uOp->getSubExpr()->getType();
  9792. }
  9793. // Technically, there should be a check for array subscript
  9794. // expressions here, but the result of one is always an lvalue anyway.
  9795. }
  9796. ValueDecl *dcl = getPrimaryDecl(op);
  9797. if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
  9798. if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
  9799. op->getLocStart()))
  9800. return QualType();
  9801. Expr::LValueClassification lval = op->ClassifyLValue(Context);
  9802. unsigned AddressOfError = AO_No_Error;
  9803. if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
  9804. bool sfinae = (bool)isSFINAEContext();
  9805. Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
  9806. : diag::ext_typecheck_addrof_temporary)
  9807. << op->getType() << op->getSourceRange();
  9808. if (sfinae)
  9809. return QualType();
  9810. // Materialize the temporary as an lvalue so that we can take its address.
  9811. OrigOp = op =
  9812. CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
  9813. } else if (isa<ObjCSelectorExpr>(op)) {
  9814. return Context.getPointerType(op->getType());
  9815. } else if (lval == Expr::LV_MemberFunction) {
  9816. // If it's an instance method, make a member pointer.
  9817. // The expression must have exactly the form &A::foo.
  9818. // If the underlying expression isn't a decl ref, give up.
  9819. if (!isa<DeclRefExpr>(op)) {
  9820. Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
  9821. << OrigOp.get()->getSourceRange();
  9822. return QualType();
  9823. }
  9824. DeclRefExpr *DRE = cast<DeclRefExpr>(op);
  9825. CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
  9826. // The id-expression was parenthesized.
  9827. if (OrigOp.get() != DRE) {
  9828. Diag(OpLoc, diag::err_parens_pointer_member_function)
  9829. << OrigOp.get()->getSourceRange();
  9830. // The method was named without a qualifier.
  9831. } else if (!DRE->getQualifier()) {
  9832. if (MD->getParent()->getName().empty())
  9833. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  9834. << op->getSourceRange();
  9835. else {
  9836. SmallString<32> Str;
  9837. StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
  9838. Diag(OpLoc, diag::err_unqualified_pointer_member_function)
  9839. << op->getSourceRange()
  9840. << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
  9841. }
  9842. }
  9843. // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
  9844. if (isa<CXXDestructorDecl>(MD))
  9845. Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
  9846. QualType MPTy = Context.getMemberPointerType(
  9847. op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
  9848. // Under the MS ABI, lock down the inheritance model now.
  9849. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  9850. (void)isCompleteType(OpLoc, MPTy);
  9851. return MPTy;
  9852. } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
  9853. // C99 6.5.3.2p1
  9854. // The operand must be either an l-value or a function designator
  9855. if (!op->getType()->isFunctionType()) {
  9856. // Use a special diagnostic for loads from property references.
  9857. if (isa<PseudoObjectExpr>(op)) {
  9858. AddressOfError = AO_Property_Expansion;
  9859. } else {
  9860. Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
  9861. << op->getType() << op->getSourceRange();
  9862. return QualType();
  9863. }
  9864. }
  9865. } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
  9866. // The operand cannot be a bit-field
  9867. AddressOfError = AO_Bit_Field;
  9868. } else if (op->getObjectKind() == OK_VectorComponent) {
  9869. // The operand cannot be an element of a vector
  9870. AddressOfError = AO_Vector_Element;
  9871. } else if (dcl) { // C99 6.5.3.2p1
  9872. // We have an lvalue with a decl. Make sure the decl is not declared
  9873. // with the register storage-class specifier.
  9874. if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
  9875. // in C++ it is not error to take address of a register
  9876. // variable (c++03 7.1.1P3)
  9877. if (vd->getStorageClass() == SC_Register &&
  9878. !getLangOpts().CPlusPlus) {
  9879. AddressOfError = AO_Register_Variable;
  9880. }
  9881. } else if (isa<MSPropertyDecl>(dcl)) {
  9882. AddressOfError = AO_Property_Expansion;
  9883. } else if (isa<FunctionTemplateDecl>(dcl)) {
  9884. return Context.OverloadTy;
  9885. } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
  9886. // Okay: we can take the address of a field.
  9887. // Could be a pointer to member, though, if there is an explicit
  9888. // scope qualifier for the class.
  9889. if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
  9890. DeclContext *Ctx = dcl->getDeclContext();
  9891. if (Ctx && Ctx->isRecord()) {
  9892. if (dcl->getType()->isReferenceType()) {
  9893. Diag(OpLoc,
  9894. diag::err_cannot_form_pointer_to_member_of_reference_type)
  9895. << dcl->getDeclName() << dcl->getType();
  9896. return QualType();
  9897. }
  9898. while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
  9899. Ctx = Ctx->getParent();
  9900. QualType MPTy = Context.getMemberPointerType(
  9901. op->getType(),
  9902. Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
  9903. // Under the MS ABI, lock down the inheritance model now.
  9904. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  9905. (void)isCompleteType(OpLoc, MPTy);
  9906. return MPTy;
  9907. }
  9908. }
  9909. } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
  9910. !isa<BindingDecl>(dcl))
  9911. llvm_unreachable("Unknown/unexpected decl type");
  9912. }
  9913. if (AddressOfError != AO_No_Error) {
  9914. diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
  9915. return QualType();
  9916. }
  9917. if (lval == Expr::LV_IncompleteVoidType) {
  9918. // Taking the address of a void variable is technically illegal, but we
  9919. // allow it in cases which are otherwise valid.
  9920. // Example: "extern void x; void* y = &x;".
  9921. Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
  9922. }
  9923. // If the operand has type "type", the result has type "pointer to type".
  9924. if (op->getType()->isObjCObjectType())
  9925. return Context.getObjCObjectPointerType(op->getType());
  9926. CheckAddressOfPackedMember(op);
  9927. return Context.getPointerType(op->getType());
  9928. }
  9929. static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
  9930. const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
  9931. if (!DRE)
  9932. return;
  9933. const Decl *D = DRE->getDecl();
  9934. if (!D)
  9935. return;
  9936. const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
  9937. if (!Param)
  9938. return;
  9939. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
  9940. if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
  9941. return;
  9942. if (FunctionScopeInfo *FD = S.getCurFunction())
  9943. if (!FD->ModifiedNonNullParams.count(Param))
  9944. FD->ModifiedNonNullParams.insert(Param);
  9945. }
  9946. /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
  9947. static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
  9948. SourceLocation OpLoc) {
  9949. if (Op->isTypeDependent())
  9950. return S.Context.DependentTy;
  9951. ExprResult ConvResult = S.UsualUnaryConversions(Op);
  9952. if (ConvResult.isInvalid())
  9953. return QualType();
  9954. Op = ConvResult.get();
  9955. QualType OpTy = Op->getType();
  9956. QualType Result;
  9957. if (isa<CXXReinterpretCastExpr>(Op)) {
  9958. QualType OpOrigType = Op->IgnoreParenCasts()->getType();
  9959. S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
  9960. Op->getSourceRange());
  9961. }
  9962. if (const PointerType *PT = OpTy->getAs<PointerType>())
  9963. {
  9964. Result = PT->getPointeeType();
  9965. }
  9966. else if (const ObjCObjectPointerType *OPT =
  9967. OpTy->getAs<ObjCObjectPointerType>())
  9968. Result = OPT->getPointeeType();
  9969. else {
  9970. ExprResult PR = S.CheckPlaceholderExpr(Op);
  9971. if (PR.isInvalid()) return QualType();
  9972. if (PR.get() != Op)
  9973. return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
  9974. }
  9975. if (Result.isNull()) {
  9976. S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
  9977. << OpTy << Op->getSourceRange();
  9978. return QualType();
  9979. }
  9980. // Note that per both C89 and C99, indirection is always legal, even if Result
  9981. // is an incomplete type or void. It would be possible to warn about
  9982. // dereferencing a void pointer, but it's completely well-defined, and such a
  9983. // warning is unlikely to catch any mistakes. In C++, indirection is not valid
  9984. // for pointers to 'void' but is fine for any other pointer type:
  9985. //
  9986. // C++ [expr.unary.op]p1:
  9987. // [...] the expression to which [the unary * operator] is applied shall
  9988. // be a pointer to an object type, or a pointer to a function type
  9989. if (S.getLangOpts().CPlusPlus && Result->isVoidType())
  9990. S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
  9991. << OpTy << Op->getSourceRange();
  9992. // Dereferences are usually l-values...
  9993. VK = VK_LValue;
  9994. // ...except that certain expressions are never l-values in C.
  9995. if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
  9996. VK = VK_RValue;
  9997. return Result;
  9998. }
  9999. BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
  10000. BinaryOperatorKind Opc;
  10001. switch (Kind) {
  10002. default: llvm_unreachable("Unknown binop!");
  10003. case tok::periodstar: Opc = BO_PtrMemD; break;
  10004. case tok::arrowstar: Opc = BO_PtrMemI; break;
  10005. case tok::star: Opc = BO_Mul; break;
  10006. case tok::slash: Opc = BO_Div; break;
  10007. case tok::percent: Opc = BO_Rem; break;
  10008. case tok::plus: Opc = BO_Add; break;
  10009. case tok::minus: Opc = BO_Sub; break;
  10010. case tok::lessless: Opc = BO_Shl; break;
  10011. case tok::greatergreater: Opc = BO_Shr; break;
  10012. case tok::lessequal: Opc = BO_LE; break;
  10013. case tok::less: Opc = BO_LT; break;
  10014. case tok::greaterequal: Opc = BO_GE; break;
  10015. case tok::greater: Opc = BO_GT; break;
  10016. case tok::exclaimequal: Opc = BO_NE; break;
  10017. case tok::equalequal: Opc = BO_EQ; break;
  10018. case tok::spaceship: Opc = BO_Cmp; break;
  10019. case tok::amp: Opc = BO_And; break;
  10020. case tok::caret: Opc = BO_Xor; break;
  10021. case tok::pipe: Opc = BO_Or; break;
  10022. case tok::ampamp: Opc = BO_LAnd; break;
  10023. case tok::pipepipe: Opc = BO_LOr; break;
  10024. case tok::equal: Opc = BO_Assign; break;
  10025. case tok::starequal: Opc = BO_MulAssign; break;
  10026. case tok::slashequal: Opc = BO_DivAssign; break;
  10027. case tok::percentequal: Opc = BO_RemAssign; break;
  10028. case tok::plusequal: Opc = BO_AddAssign; break;
  10029. case tok::minusequal: Opc = BO_SubAssign; break;
  10030. case tok::lesslessequal: Opc = BO_ShlAssign; break;
  10031. case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
  10032. case tok::ampequal: Opc = BO_AndAssign; break;
  10033. case tok::caretequal: Opc = BO_XorAssign; break;
  10034. case tok::pipeequal: Opc = BO_OrAssign; break;
  10035. case tok::comma: Opc = BO_Comma; break;
  10036. }
  10037. return Opc;
  10038. }
  10039. static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
  10040. tok::TokenKind Kind) {
  10041. UnaryOperatorKind Opc;
  10042. switch (Kind) {
  10043. default: llvm_unreachable("Unknown unary op!");
  10044. case tok::plusplus: Opc = UO_PreInc; break;
  10045. case tok::minusminus: Opc = UO_PreDec; break;
  10046. case tok::amp: Opc = UO_AddrOf; break;
  10047. case tok::star: Opc = UO_Deref; break;
  10048. case tok::plus: Opc = UO_Plus; break;
  10049. case tok::minus: Opc = UO_Minus; break;
  10050. case tok::tilde: Opc = UO_Not; break;
  10051. case tok::exclaim: Opc = UO_LNot; break;
  10052. case tok::kw___real: Opc = UO_Real; break;
  10053. case tok::kw___imag: Opc = UO_Imag; break;
  10054. case tok::kw___extension__: Opc = UO_Extension; break;
  10055. }
  10056. return Opc;
  10057. }
  10058. /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
  10059. /// This warning is only emitted for builtin assignment operations. It is also
  10060. /// suppressed in the event of macro expansions.
  10061. static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
  10062. SourceLocation OpLoc) {
  10063. if (S.inTemplateInstantiation())
  10064. return;
  10065. if (OpLoc.isInvalid() || OpLoc.isMacroID())
  10066. return;
  10067. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  10068. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  10069. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  10070. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  10071. if (!LHSDeclRef || !RHSDeclRef ||
  10072. LHSDeclRef->getLocation().isMacroID() ||
  10073. RHSDeclRef->getLocation().isMacroID())
  10074. return;
  10075. const ValueDecl *LHSDecl =
  10076. cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
  10077. const ValueDecl *RHSDecl =
  10078. cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
  10079. if (LHSDecl != RHSDecl)
  10080. return;
  10081. if (LHSDecl->getType().isVolatileQualified())
  10082. return;
  10083. if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
  10084. if (RefTy->getPointeeType().isVolatileQualified())
  10085. return;
  10086. S.Diag(OpLoc, diag::warn_self_assignment)
  10087. << LHSDeclRef->getType()
  10088. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
  10089. }
  10090. /// Check if a bitwise-& is performed on an Objective-C pointer. This
  10091. /// is usually indicative of introspection within the Objective-C pointer.
  10092. static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
  10093. SourceLocation OpLoc) {
  10094. if (!S.getLangOpts().ObjC1)
  10095. return;
  10096. const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
  10097. const Expr *LHS = L.get();
  10098. const Expr *RHS = R.get();
  10099. if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10100. ObjCPointerExpr = LHS;
  10101. OtherExpr = RHS;
  10102. }
  10103. else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
  10104. ObjCPointerExpr = RHS;
  10105. OtherExpr = LHS;
  10106. }
  10107. // This warning is deliberately made very specific to reduce false
  10108. // positives with logic that uses '&' for hashing. This logic mainly
  10109. // looks for code trying to introspect into tagged pointers, which
  10110. // code should generally never do.
  10111. if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
  10112. unsigned Diag = diag::warn_objc_pointer_masking;
  10113. // Determine if we are introspecting the result of performSelectorXXX.
  10114. const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
  10115. // Special case messages to -performSelector and friends, which
  10116. // can return non-pointer values boxed in a pointer value.
  10117. // Some clients may wish to silence warnings in this subcase.
  10118. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
  10119. Selector S = ME->getSelector();
  10120. StringRef SelArg0 = S.getNameForSlot(0);
  10121. if (SelArg0.startswith("performSelector"))
  10122. Diag = diag::warn_objc_pointer_masking_performSelector;
  10123. }
  10124. S.Diag(OpLoc, Diag)
  10125. << ObjCPointerExpr->getSourceRange();
  10126. }
  10127. }
  10128. static NamedDecl *getDeclFromExpr(Expr *E) {
  10129. if (!E)
  10130. return nullptr;
  10131. if (auto *DRE = dyn_cast<DeclRefExpr>(E))
  10132. return DRE->getDecl();
  10133. if (auto *ME = dyn_cast<MemberExpr>(E))
  10134. return ME->getMemberDecl();
  10135. if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
  10136. return IRE->getDecl();
  10137. return nullptr;
  10138. }
  10139. // This helper function promotes a binary operator's operands (which are of a
  10140. // half vector type) to a vector of floats and then truncates the result to
  10141. // a vector of either half or short.
  10142. static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
  10143. BinaryOperatorKind Opc, QualType ResultTy,
  10144. ExprValueKind VK, ExprObjectKind OK,
  10145. bool IsCompAssign, SourceLocation OpLoc,
  10146. FPOptions FPFeatures) {
  10147. auto &Context = S.getASTContext();
  10148. assert((isVector(ResultTy, Context.HalfTy) ||
  10149. isVector(ResultTy, Context.ShortTy)) &&
  10150. "Result must be a vector of half or short");
  10151. assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
  10152. isVector(RHS.get()->getType(), Context.HalfTy) &&
  10153. "both operands expected to be a half vector");
  10154. RHS = convertVector(RHS.get(), Context.FloatTy, S);
  10155. QualType BinOpResTy = RHS.get()->getType();
  10156. // If Opc is a comparison, ResultType is a vector of shorts. In that case,
  10157. // change BinOpResTy to a vector of ints.
  10158. if (isVector(ResultTy, Context.ShortTy))
  10159. BinOpResTy = S.GetSignedVectorType(BinOpResTy);
  10160. if (IsCompAssign)
  10161. return new (Context) CompoundAssignOperator(
  10162. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
  10163. OpLoc, FPFeatures);
  10164. LHS = convertVector(LHS.get(), Context.FloatTy, S);
  10165. auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
  10166. VK, OK, OpLoc, FPFeatures);
  10167. return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
  10168. }
  10169. static std::pair<ExprResult, ExprResult>
  10170. CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
  10171. Expr *RHSExpr) {
  10172. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10173. if (!S.getLangOpts().CPlusPlus) {
  10174. // C cannot handle TypoExpr nodes on either side of a binop because it
  10175. // doesn't handle dependent types properly, so make sure any TypoExprs have
  10176. // been dealt with before checking the operands.
  10177. LHS = S.CorrectDelayedTyposInExpr(LHS);
  10178. RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
  10179. if (Opc != BO_Assign)
  10180. return ExprResult(E);
  10181. // Avoid correcting the RHS to the same Expr as the LHS.
  10182. Decl *D = getDeclFromExpr(E);
  10183. return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
  10184. });
  10185. }
  10186. return std::make_pair(LHS, RHS);
  10187. }
  10188. /// Returns true if conversion between vectors of halfs and vectors of floats
  10189. /// is needed.
  10190. static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
  10191. QualType SrcType) {
  10192. return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
  10193. !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
  10194. isVector(SrcType, Ctx.HalfTy);
  10195. }
  10196. /// CreateBuiltinBinOp - Creates a new built-in binary operation with
  10197. /// operator @p Opc at location @c TokLoc. This routine only supports
  10198. /// built-in operations; ActOnBinOp handles overloaded operators.
  10199. ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
  10200. BinaryOperatorKind Opc,
  10201. Expr *LHSExpr, Expr *RHSExpr) {
  10202. if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
  10203. // The syntax only allows initializer lists on the RHS of assignment,
  10204. // so we don't need to worry about accepting invalid code for
  10205. // non-assignment operators.
  10206. // C++11 5.17p9:
  10207. // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
  10208. // of x = {} is x = T().
  10209. InitializationKind Kind =
  10210. InitializationKind::CreateDirectList(RHSExpr->getLocStart());
  10211. InitializedEntity Entity =
  10212. InitializedEntity::InitializeTemporary(LHSExpr->getType());
  10213. InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
  10214. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
  10215. if (Init.isInvalid())
  10216. return Init;
  10217. RHSExpr = Init.get();
  10218. }
  10219. ExprResult LHS = LHSExpr, RHS = RHSExpr;
  10220. QualType ResultTy; // Result type of the binary operator.
  10221. // The following two variables are used for compound assignment operators
  10222. QualType CompLHSTy; // Type of LHS after promotions for computation
  10223. QualType CompResultTy; // Type of computation result
  10224. ExprValueKind VK = VK_RValue;
  10225. ExprObjectKind OK = OK_Ordinary;
  10226. bool ConvertHalfVec = false;
  10227. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  10228. if (!LHS.isUsable() || !RHS.isUsable())
  10229. return ExprError();
  10230. if (getLangOpts().OpenCL) {
  10231. QualType LHSTy = LHSExpr->getType();
  10232. QualType RHSTy = RHSExpr->getType();
  10233. // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
  10234. // the ATOMIC_VAR_INIT macro.
  10235. if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
  10236. SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
  10237. if (BO_Assign == Opc)
  10238. Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
  10239. else
  10240. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10241. return ExprError();
  10242. }
  10243. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  10244. // only with a builtin functions and therefore should be disallowed here.
  10245. if (LHSTy->isImageType() || RHSTy->isImageType() ||
  10246. LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
  10247. LHSTy->isPipeType() || RHSTy->isPipeType() ||
  10248. LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
  10249. ResultTy = InvalidOperands(OpLoc, LHS, RHS);
  10250. return ExprError();
  10251. }
  10252. }
  10253. switch (Opc) {
  10254. case BO_Assign:
  10255. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
  10256. if (getLangOpts().CPlusPlus &&
  10257. LHS.get()->getObjectKind() != OK_ObjCProperty) {
  10258. VK = LHS.get()->getValueKind();
  10259. OK = LHS.get()->getObjectKind();
  10260. }
  10261. if (!ResultTy.isNull()) {
  10262. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  10263. DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
  10264. }
  10265. RecordModifiableNonNullParam(*this, LHS.get());
  10266. break;
  10267. case BO_PtrMemD:
  10268. case BO_PtrMemI:
  10269. ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
  10270. Opc == BO_PtrMemI);
  10271. break;
  10272. case BO_Mul:
  10273. case BO_Div:
  10274. ConvertHalfVec = true;
  10275. ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
  10276. Opc == BO_Div);
  10277. break;
  10278. case BO_Rem:
  10279. ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
  10280. break;
  10281. case BO_Add:
  10282. ConvertHalfVec = true;
  10283. ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
  10284. break;
  10285. case BO_Sub:
  10286. ConvertHalfVec = true;
  10287. ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
  10288. break;
  10289. case BO_Shl:
  10290. case BO_Shr:
  10291. ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
  10292. break;
  10293. case BO_LE:
  10294. case BO_LT:
  10295. case BO_GE:
  10296. case BO_GT:
  10297. ConvertHalfVec = true;
  10298. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  10299. break;
  10300. case BO_EQ:
  10301. case BO_NE:
  10302. ConvertHalfVec = true;
  10303. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
  10304. break;
  10305. case BO_Cmp:
  10306. // FIXME: Implement proper semantic checking of '<=>'.
  10307. ConvertHalfVec = true;
  10308. ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
  10309. if (!ResultTy.isNull())
  10310. ResultTy = Context.VoidTy;
  10311. break;
  10312. case BO_And:
  10313. checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
  10314. LLVM_FALLTHROUGH;
  10315. case BO_Xor:
  10316. case BO_Or:
  10317. ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  10318. break;
  10319. case BO_LAnd:
  10320. case BO_LOr:
  10321. ConvertHalfVec = true;
  10322. ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
  10323. break;
  10324. case BO_MulAssign:
  10325. case BO_DivAssign:
  10326. ConvertHalfVec = true;
  10327. CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
  10328. Opc == BO_DivAssign);
  10329. CompLHSTy = CompResultTy;
  10330. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10331. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10332. break;
  10333. case BO_RemAssign:
  10334. CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
  10335. CompLHSTy = CompResultTy;
  10336. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10337. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10338. break;
  10339. case BO_AddAssign:
  10340. ConvertHalfVec = true;
  10341. CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
  10342. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10343. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10344. break;
  10345. case BO_SubAssign:
  10346. ConvertHalfVec = true;
  10347. CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
  10348. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10349. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10350. break;
  10351. case BO_ShlAssign:
  10352. case BO_ShrAssign:
  10353. CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
  10354. CompLHSTy = CompResultTy;
  10355. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10356. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10357. break;
  10358. case BO_AndAssign:
  10359. case BO_OrAssign: // fallthrough
  10360. DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
  10361. LLVM_FALLTHROUGH;
  10362. case BO_XorAssign:
  10363. CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
  10364. CompLHSTy = CompResultTy;
  10365. if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
  10366. ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
  10367. break;
  10368. case BO_Comma:
  10369. ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
  10370. if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
  10371. VK = RHS.get()->getValueKind();
  10372. OK = RHS.get()->getObjectKind();
  10373. }
  10374. break;
  10375. }
  10376. if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
  10377. return ExprError();
  10378. // Some of the binary operations require promoting operands of half vector to
  10379. // float vectors and truncating the result back to half vector. For now, we do
  10380. // this only when HalfArgsAndReturn is set (that is, when the target is arm or
  10381. // arm64).
  10382. assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
  10383. isVector(LHS.get()->getType(), Context.HalfTy) &&
  10384. "both sides are half vectors or neither sides are");
  10385. ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
  10386. LHS.get()->getType());
  10387. // Check for array bounds violations for both sides of the BinaryOperator
  10388. CheckArrayAccess(LHS.get());
  10389. CheckArrayAccess(RHS.get());
  10390. if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
  10391. NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
  10392. &Context.Idents.get("object_setClass"),
  10393. SourceLocation(), LookupOrdinaryName);
  10394. if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
  10395. SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
  10396. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
  10397. FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
  10398. FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
  10399. FixItHint::CreateInsertion(RHSLocEnd, ")");
  10400. }
  10401. else
  10402. Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
  10403. }
  10404. else if (const ObjCIvarRefExpr *OIRE =
  10405. dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
  10406. DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
  10407. // Opc is not a compound assignment if CompResultTy is null.
  10408. if (CompResultTy.isNull()) {
  10409. if (ConvertHalfVec)
  10410. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
  10411. OpLoc, FPFeatures);
  10412. return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
  10413. OK, OpLoc, FPFeatures);
  10414. }
  10415. // Handle compound assignments.
  10416. if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
  10417. OK_ObjCProperty) {
  10418. VK = VK_LValue;
  10419. OK = LHS.get()->getObjectKind();
  10420. }
  10421. if (ConvertHalfVec)
  10422. return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
  10423. OpLoc, FPFeatures);
  10424. return new (Context) CompoundAssignOperator(
  10425. LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
  10426. OpLoc, FPFeatures);
  10427. }
  10428. /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
  10429. /// operators are mixed in a way that suggests that the programmer forgot that
  10430. /// comparison operators have higher precedence. The most typical example of
  10431. /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
  10432. static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
  10433. SourceLocation OpLoc, Expr *LHSExpr,
  10434. Expr *RHSExpr) {
  10435. BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
  10436. BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
  10437. // Check that one of the sides is a comparison operator and the other isn't.
  10438. bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
  10439. bool isRightComp = RHSBO && RHSBO->isComparisonOp();
  10440. if (isLeftComp == isRightComp)
  10441. return;
  10442. // Bitwise operations are sometimes used as eager logical ops.
  10443. // Don't diagnose this.
  10444. bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
  10445. bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
  10446. if (isLeftBitwise || isRightBitwise)
  10447. return;
  10448. SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
  10449. OpLoc)
  10450. : SourceRange(OpLoc, RHSExpr->getLocEnd());
  10451. StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
  10452. SourceRange ParensRange = isLeftComp ?
  10453. SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
  10454. : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
  10455. Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
  10456. << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
  10457. SuggestParentheses(Self, OpLoc,
  10458. Self.PDiag(diag::note_precedence_silence) << OpStr,
  10459. (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
  10460. SuggestParentheses(Self, OpLoc,
  10461. Self.PDiag(diag::note_precedence_bitwise_first)
  10462. << BinaryOperator::getOpcodeStr(Opc),
  10463. ParensRange);
  10464. }
  10465. /// \brief It accepts a '&&' expr that is inside a '||' one.
  10466. /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
  10467. /// in parentheses.
  10468. static void
  10469. EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
  10470. BinaryOperator *Bop) {
  10471. assert(Bop->getOpcode() == BO_LAnd);
  10472. Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
  10473. << Bop->getSourceRange() << OpLoc;
  10474. SuggestParentheses(Self, Bop->getOperatorLoc(),
  10475. Self.PDiag(diag::note_precedence_silence)
  10476. << Bop->getOpcodeStr(),
  10477. Bop->getSourceRange());
  10478. }
  10479. /// \brief Returns true if the given expression can be evaluated as a constant
  10480. /// 'true'.
  10481. static bool EvaluatesAsTrue(Sema &S, Expr *E) {
  10482. bool Res;
  10483. return !E->isValueDependent() &&
  10484. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
  10485. }
  10486. /// \brief Returns true if the given expression can be evaluated as a constant
  10487. /// 'false'.
  10488. static bool EvaluatesAsFalse(Sema &S, Expr *E) {
  10489. bool Res;
  10490. return !E->isValueDependent() &&
  10491. E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
  10492. }
  10493. /// \brief Look for '&&' in the left hand of a '||' expr.
  10494. static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
  10495. Expr *LHSExpr, Expr *RHSExpr) {
  10496. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
  10497. if (Bop->getOpcode() == BO_LAnd) {
  10498. // If it's "a && b || 0" don't warn since the precedence doesn't matter.
  10499. if (EvaluatesAsFalse(S, RHSExpr))
  10500. return;
  10501. // If it's "1 && a || b" don't warn since the precedence doesn't matter.
  10502. if (!EvaluatesAsTrue(S, Bop->getLHS()))
  10503. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  10504. } else if (Bop->getOpcode() == BO_LOr) {
  10505. if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
  10506. // If it's "a || b && 1 || c" we didn't warn earlier for
  10507. // "a || b && 1", but warn now.
  10508. if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
  10509. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
  10510. }
  10511. }
  10512. }
  10513. }
  10514. /// \brief Look for '&&' in the right hand of a '||' expr.
  10515. static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
  10516. Expr *LHSExpr, Expr *RHSExpr) {
  10517. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
  10518. if (Bop->getOpcode() == BO_LAnd) {
  10519. // If it's "0 || a && b" don't warn since the precedence doesn't matter.
  10520. if (EvaluatesAsFalse(S, LHSExpr))
  10521. return;
  10522. // If it's "a || b && 1" don't warn since the precedence doesn't matter.
  10523. if (!EvaluatesAsTrue(S, Bop->getRHS()))
  10524. return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
  10525. }
  10526. }
  10527. }
  10528. /// \brief Look for bitwise op in the left or right hand of a bitwise op with
  10529. /// lower precedence and emit a diagnostic together with a fixit hint that wraps
  10530. /// the '&' expression in parentheses.
  10531. static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
  10532. SourceLocation OpLoc, Expr *SubExpr) {
  10533. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  10534. if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
  10535. S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
  10536. << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
  10537. << Bop->getSourceRange() << OpLoc;
  10538. SuggestParentheses(S, Bop->getOperatorLoc(),
  10539. S.PDiag(diag::note_precedence_silence)
  10540. << Bop->getOpcodeStr(),
  10541. Bop->getSourceRange());
  10542. }
  10543. }
  10544. }
  10545. static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
  10546. Expr *SubExpr, StringRef Shift) {
  10547. if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
  10548. if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
  10549. StringRef Op = Bop->getOpcodeStr();
  10550. S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
  10551. << Bop->getSourceRange() << OpLoc << Shift << Op;
  10552. SuggestParentheses(S, Bop->getOperatorLoc(),
  10553. S.PDiag(diag::note_precedence_silence) << Op,
  10554. Bop->getSourceRange());
  10555. }
  10556. }
  10557. }
  10558. static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
  10559. Expr *LHSExpr, Expr *RHSExpr) {
  10560. CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
  10561. if (!OCE)
  10562. return;
  10563. FunctionDecl *FD = OCE->getDirectCallee();
  10564. if (!FD || !FD->isOverloadedOperator())
  10565. return;
  10566. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  10567. if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
  10568. return;
  10569. S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
  10570. << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
  10571. << (Kind == OO_LessLess);
  10572. SuggestParentheses(S, OCE->getOperatorLoc(),
  10573. S.PDiag(diag::note_precedence_silence)
  10574. << (Kind == OO_LessLess ? "<<" : ">>"),
  10575. OCE->getSourceRange());
  10576. SuggestParentheses(S, OpLoc,
  10577. S.PDiag(diag::note_evaluate_comparison_first),
  10578. SourceRange(OCE->getArg(1)->getLocStart(),
  10579. RHSExpr->getLocEnd()));
  10580. }
  10581. /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
  10582. /// precedence.
  10583. static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
  10584. SourceLocation OpLoc, Expr *LHSExpr,
  10585. Expr *RHSExpr){
  10586. // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
  10587. if (BinaryOperator::isBitwiseOp(Opc))
  10588. DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
  10589. // Diagnose "arg1 & arg2 | arg3"
  10590. if ((Opc == BO_Or || Opc == BO_Xor) &&
  10591. !OpLoc.isMacroID()/* Don't warn in macros. */) {
  10592. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
  10593. DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
  10594. }
  10595. // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
  10596. // We don't warn for 'assert(a || b && "bad")' since this is safe.
  10597. if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
  10598. DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
  10599. DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
  10600. }
  10601. if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
  10602. || Opc == BO_Shr) {
  10603. StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
  10604. DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
  10605. DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
  10606. }
  10607. // Warn on overloaded shift operators and comparisons, such as:
  10608. // cout << 5 == 4;
  10609. if (BinaryOperator::isComparisonOp(Opc))
  10610. DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
  10611. }
  10612. // Binary Operators. 'Tok' is the token for the operator.
  10613. ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
  10614. tok::TokenKind Kind,
  10615. Expr *LHSExpr, Expr *RHSExpr) {
  10616. BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
  10617. assert(LHSExpr && "ActOnBinOp(): missing left expression");
  10618. assert(RHSExpr && "ActOnBinOp(): missing right expression");
  10619. // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
  10620. DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
  10621. return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
  10622. }
  10623. /// Build an overloaded binary operator expression in the given scope.
  10624. static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
  10625. BinaryOperatorKind Opc,
  10626. Expr *LHS, Expr *RHS) {
  10627. // Find all of the overloaded operators visible from this
  10628. // point. We perform both an operator-name lookup from the local
  10629. // scope and an argument-dependent lookup based on the types of
  10630. // the arguments.
  10631. UnresolvedSet<16> Functions;
  10632. OverloadedOperatorKind OverOp
  10633. = BinaryOperator::getOverloadedOperator(Opc);
  10634. if (Sc && OverOp != OO_None && OverOp != OO_Equal)
  10635. S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
  10636. RHS->getType(), Functions);
  10637. // Build the (potentially-overloaded, potentially-dependent)
  10638. // binary operation.
  10639. return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
  10640. }
  10641. ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
  10642. BinaryOperatorKind Opc,
  10643. Expr *LHSExpr, Expr *RHSExpr) {
  10644. ExprResult LHS, RHS;
  10645. std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
  10646. if (!LHS.isUsable() || !RHS.isUsable())
  10647. return ExprError();
  10648. LHSExpr = LHS.get();
  10649. RHSExpr = RHS.get();
  10650. // We want to end up calling one of checkPseudoObjectAssignment
  10651. // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
  10652. // both expressions are overloadable or either is type-dependent),
  10653. // or CreateBuiltinBinOp (in any other case). We also want to get
  10654. // any placeholder types out of the way.
  10655. // Handle pseudo-objects in the LHS.
  10656. if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
  10657. // Assignments with a pseudo-object l-value need special analysis.
  10658. if (pty->getKind() == BuiltinType::PseudoObject &&
  10659. BinaryOperator::isAssignmentOp(Opc))
  10660. return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
  10661. // Don't resolve overloads if the other type is overloadable.
  10662. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
  10663. // We can't actually test that if we still have a placeholder,
  10664. // though. Fortunately, none of the exceptions we see in that
  10665. // code below are valid when the LHS is an overload set. Note
  10666. // that an overload set can be dependently-typed, but it never
  10667. // instantiates to having an overloadable type.
  10668. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  10669. if (resolvedRHS.isInvalid()) return ExprError();
  10670. RHSExpr = resolvedRHS.get();
  10671. if (RHSExpr->isTypeDependent() ||
  10672. RHSExpr->getType()->isOverloadableType())
  10673. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  10674. }
  10675. // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
  10676. // template, diagnose the missing 'template' keyword instead of diagnosing
  10677. // an invalid use of a bound member function.
  10678. //
  10679. // Note that "A::x < b" might be valid if 'b' has an overloadable type due
  10680. // to C++1z [over.over]/1.4, but we already checked for that case above.
  10681. if (Opc == BO_LT && inTemplateInstantiation() &&
  10682. (pty->getKind() == BuiltinType::BoundMember ||
  10683. pty->getKind() == BuiltinType::Overload)) {
  10684. auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
  10685. if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
  10686. std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
  10687. return isa<FunctionTemplateDecl>(ND);
  10688. })) {
  10689. Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
  10690. : OE->getNameLoc(),
  10691. diag::err_template_kw_missing)
  10692. << OE->getName().getAsString() << "";
  10693. return ExprError();
  10694. }
  10695. }
  10696. ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
  10697. if (LHS.isInvalid()) return ExprError();
  10698. LHSExpr = LHS.get();
  10699. }
  10700. // Handle pseudo-objects in the RHS.
  10701. if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
  10702. // An overload in the RHS can potentially be resolved by the type
  10703. // being assigned to.
  10704. if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
  10705. if (getLangOpts().CPlusPlus &&
  10706. (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
  10707. LHSExpr->getType()->isOverloadableType()))
  10708. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  10709. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  10710. }
  10711. // Don't resolve overloads if the other type is overloadable.
  10712. if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
  10713. LHSExpr->getType()->isOverloadableType())
  10714. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  10715. ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
  10716. if (!resolvedRHS.isUsable()) return ExprError();
  10717. RHSExpr = resolvedRHS.get();
  10718. }
  10719. if (getLangOpts().CPlusPlus) {
  10720. // If either expression is type-dependent, always build an
  10721. // overloaded op.
  10722. if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
  10723. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  10724. // Otherwise, build an overloaded op if either expression has an
  10725. // overloadable type.
  10726. if (LHSExpr->getType()->isOverloadableType() ||
  10727. RHSExpr->getType()->isOverloadableType())
  10728. return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
  10729. }
  10730. // Build a built-in binary operation.
  10731. return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
  10732. }
  10733. ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
  10734. UnaryOperatorKind Opc,
  10735. Expr *InputExpr) {
  10736. ExprResult Input = InputExpr;
  10737. ExprValueKind VK = VK_RValue;
  10738. ExprObjectKind OK = OK_Ordinary;
  10739. QualType resultType;
  10740. bool ConvertHalfVec = false;
  10741. if (getLangOpts().OpenCL) {
  10742. QualType Ty = InputExpr->getType();
  10743. // The only legal unary operation for atomics is '&'.
  10744. if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
  10745. // OpenCL special types - image, sampler, pipe, and blocks are to be used
  10746. // only with a builtin functions and therefore should be disallowed here.
  10747. (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
  10748. || Ty->isBlockPointerType())) {
  10749. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10750. << InputExpr->getType()
  10751. << Input.get()->getSourceRange());
  10752. }
  10753. }
  10754. switch (Opc) {
  10755. case UO_PreInc:
  10756. case UO_PreDec:
  10757. case UO_PostInc:
  10758. case UO_PostDec:
  10759. resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
  10760. OpLoc,
  10761. Opc == UO_PreInc ||
  10762. Opc == UO_PostInc,
  10763. Opc == UO_PreInc ||
  10764. Opc == UO_PreDec);
  10765. break;
  10766. case UO_AddrOf:
  10767. resultType = CheckAddressOfOperand(Input, OpLoc);
  10768. RecordModifiableNonNullParam(*this, InputExpr);
  10769. break;
  10770. case UO_Deref: {
  10771. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  10772. if (Input.isInvalid()) return ExprError();
  10773. resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
  10774. break;
  10775. }
  10776. case UO_Plus:
  10777. case UO_Minus:
  10778. Input = UsualUnaryConversions(Input.get());
  10779. if (Input.isInvalid()) return ExprError();
  10780. // Unary plus and minus require promoting an operand of half vector to a
  10781. // float vector and truncating the result back to a half vector. For now, we
  10782. // do this only when HalfArgsAndReturns is set (that is, when the target is
  10783. // arm or arm64).
  10784. ConvertHalfVec =
  10785. needsConversionOfHalfVec(true, Context, Input.get()->getType());
  10786. // If the operand is a half vector, promote it to a float vector.
  10787. if (ConvertHalfVec)
  10788. Input = convertVector(Input.get(), Context.FloatTy, *this);
  10789. resultType = Input.get()->getType();
  10790. if (resultType->isDependentType())
  10791. break;
  10792. if (resultType->isArithmeticType()) // C99 6.5.3.3p1
  10793. break;
  10794. else if (resultType->isVectorType() &&
  10795. // The z vector extensions don't allow + or - with bool vectors.
  10796. (!Context.getLangOpts().ZVector ||
  10797. resultType->getAs<VectorType>()->getVectorKind() !=
  10798. VectorType::AltiVecBool))
  10799. break;
  10800. else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
  10801. Opc == UO_Plus &&
  10802. resultType->isPointerType())
  10803. break;
  10804. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10805. << resultType << Input.get()->getSourceRange());
  10806. case UO_Not: // bitwise complement
  10807. Input = UsualUnaryConversions(Input.get());
  10808. if (Input.isInvalid())
  10809. return ExprError();
  10810. resultType = Input.get()->getType();
  10811. if (resultType->isDependentType())
  10812. break;
  10813. // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
  10814. if (resultType->isComplexType() || resultType->isComplexIntegerType())
  10815. // C99 does not support '~' for complex conjugation.
  10816. Diag(OpLoc, diag::ext_integer_complement_complex)
  10817. << resultType << Input.get()->getSourceRange();
  10818. else if (resultType->hasIntegerRepresentation())
  10819. break;
  10820. else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
  10821. // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
  10822. // on vector float types.
  10823. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  10824. if (!T->isIntegerType())
  10825. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10826. << resultType << Input.get()->getSourceRange());
  10827. } else {
  10828. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10829. << resultType << Input.get()->getSourceRange());
  10830. }
  10831. break;
  10832. case UO_LNot: // logical negation
  10833. // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
  10834. Input = DefaultFunctionArrayLvalueConversion(Input.get());
  10835. if (Input.isInvalid()) return ExprError();
  10836. resultType = Input.get()->getType();
  10837. // Though we still have to promote half FP to float...
  10838. if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
  10839. Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
  10840. resultType = Context.FloatTy;
  10841. }
  10842. if (resultType->isDependentType())
  10843. break;
  10844. if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
  10845. // C99 6.5.3.3p1: ok, fallthrough;
  10846. if (Context.getLangOpts().CPlusPlus) {
  10847. // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
  10848. // operand contextually converted to bool.
  10849. Input = ImpCastExprToType(Input.get(), Context.BoolTy,
  10850. ScalarTypeToBooleanCastKind(resultType));
  10851. } else if (Context.getLangOpts().OpenCL &&
  10852. Context.getLangOpts().OpenCLVersion < 120) {
  10853. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  10854. // operate on scalar float types.
  10855. if (!resultType->isIntegerType() && !resultType->isPointerType())
  10856. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10857. << resultType << Input.get()->getSourceRange());
  10858. }
  10859. } else if (resultType->isExtVectorType()) {
  10860. if (Context.getLangOpts().OpenCL &&
  10861. Context.getLangOpts().OpenCLVersion < 120) {
  10862. // OpenCL v1.1 6.3.h: The logical operator not (!) does not
  10863. // operate on vector float types.
  10864. QualType T = resultType->getAs<ExtVectorType>()->getElementType();
  10865. if (!T->isIntegerType())
  10866. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10867. << resultType << Input.get()->getSourceRange());
  10868. }
  10869. // Vector logical not returns the signed variant of the operand type.
  10870. resultType = GetSignedVectorType(resultType);
  10871. break;
  10872. } else {
  10873. // FIXME: GCC's vector extension permits the usage of '!' with a vector
  10874. // type in C++. We should allow that here too.
  10875. return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
  10876. << resultType << Input.get()->getSourceRange());
  10877. }
  10878. // LNot always has type int. C99 6.5.3.3p5.
  10879. // In C++, it's bool. C++ 5.3.1p8
  10880. resultType = Context.getLogicalOperationType();
  10881. break;
  10882. case UO_Real:
  10883. case UO_Imag:
  10884. resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
  10885. // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
  10886. // complex l-values to ordinary l-values and all other values to r-values.
  10887. if (Input.isInvalid()) return ExprError();
  10888. if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
  10889. if (Input.get()->getValueKind() != VK_RValue &&
  10890. Input.get()->getObjectKind() == OK_Ordinary)
  10891. VK = Input.get()->getValueKind();
  10892. } else if (!getLangOpts().CPlusPlus) {
  10893. // In C, a volatile scalar is read by __imag. In C++, it is not.
  10894. Input = DefaultLvalueConversion(Input.get());
  10895. }
  10896. break;
  10897. case UO_Extension:
  10898. resultType = Input.get()->getType();
  10899. VK = Input.get()->getValueKind();
  10900. OK = Input.get()->getObjectKind();
  10901. break;
  10902. case UO_Coawait:
  10903. // It's unnessesary to represent the pass-through operator co_await in the
  10904. // AST; just return the input expression instead.
  10905. assert(!Input.get()->getType()->isDependentType() &&
  10906. "the co_await expression must be non-dependant before "
  10907. "building operator co_await");
  10908. return Input;
  10909. }
  10910. if (resultType.isNull() || Input.isInvalid())
  10911. return ExprError();
  10912. // Check for array bounds violations in the operand of the UnaryOperator,
  10913. // except for the '*' and '&' operators that have to be handled specially
  10914. // by CheckArrayAccess (as there are special cases like &array[arraysize]
  10915. // that are explicitly defined as valid by the standard).
  10916. if (Opc != UO_AddrOf && Opc != UO_Deref)
  10917. CheckArrayAccess(Input.get());
  10918. auto *UO = new (Context)
  10919. UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
  10920. // Convert the result back to a half vector.
  10921. if (ConvertHalfVec)
  10922. return convertVector(UO, Context.HalfTy, *this);
  10923. return UO;
  10924. }
  10925. /// \brief Determine whether the given expression is a qualified member
  10926. /// access expression, of a form that could be turned into a pointer to member
  10927. /// with the address-of operator.
  10928. static bool isQualifiedMemberAccess(Expr *E) {
  10929. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  10930. if (!DRE->getQualifier())
  10931. return false;
  10932. ValueDecl *VD = DRE->getDecl();
  10933. if (!VD->isCXXClassMember())
  10934. return false;
  10935. if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
  10936. return true;
  10937. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
  10938. return Method->isInstance();
  10939. return false;
  10940. }
  10941. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
  10942. if (!ULE->getQualifier())
  10943. return false;
  10944. for (NamedDecl *D : ULE->decls()) {
  10945. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  10946. if (Method->isInstance())
  10947. return true;
  10948. } else {
  10949. // Overload set does not contain methods.
  10950. break;
  10951. }
  10952. }
  10953. return false;
  10954. }
  10955. return false;
  10956. }
  10957. ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
  10958. UnaryOperatorKind Opc, Expr *Input) {
  10959. // First things first: handle placeholders so that the
  10960. // overloaded-operator check considers the right type.
  10961. if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
  10962. // Increment and decrement of pseudo-object references.
  10963. if (pty->getKind() == BuiltinType::PseudoObject &&
  10964. UnaryOperator::isIncrementDecrementOp(Opc))
  10965. return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
  10966. // extension is always a builtin operator.
  10967. if (Opc == UO_Extension)
  10968. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10969. // & gets special logic for several kinds of placeholder.
  10970. // The builtin code knows what to do.
  10971. if (Opc == UO_AddrOf &&
  10972. (pty->getKind() == BuiltinType::Overload ||
  10973. pty->getKind() == BuiltinType::UnknownAny ||
  10974. pty->getKind() == BuiltinType::BoundMember))
  10975. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10976. // Anything else needs to be handled now.
  10977. ExprResult Result = CheckPlaceholderExpr(Input);
  10978. if (Result.isInvalid()) return ExprError();
  10979. Input = Result.get();
  10980. }
  10981. if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
  10982. UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
  10983. !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
  10984. // Find all of the overloaded operators visible from this
  10985. // point. We perform both an operator-name lookup from the local
  10986. // scope and an argument-dependent lookup based on the types of
  10987. // the arguments.
  10988. UnresolvedSet<16> Functions;
  10989. OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
  10990. if (S && OverOp != OO_None)
  10991. LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
  10992. Functions);
  10993. return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
  10994. }
  10995. return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
  10996. }
  10997. // Unary Operators. 'Tok' is the token for the operator.
  10998. ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
  10999. tok::TokenKind Op, Expr *Input) {
  11000. return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
  11001. }
  11002. /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
  11003. ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
  11004. LabelDecl *TheDecl) {
  11005. TheDecl->markUsed(Context);
  11006. // Create the AST node. The address of a label always has type 'void*'.
  11007. return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
  11008. Context.getPointerType(Context.VoidTy));
  11009. }
  11010. /// Given the last statement in a statement-expression, check whether
  11011. /// the result is a producing expression (like a call to an
  11012. /// ns_returns_retained function) and, if so, rebuild it to hoist the
  11013. /// release out of the full-expression. Otherwise, return null.
  11014. /// Cannot fail.
  11015. static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
  11016. // Should always be wrapped with one of these.
  11017. ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
  11018. if (!cleanups) return nullptr;
  11019. ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
  11020. if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
  11021. return nullptr;
  11022. // Splice out the cast. This shouldn't modify any interesting
  11023. // features of the statement.
  11024. Expr *producer = cast->getSubExpr();
  11025. assert(producer->getType() == cast->getType());
  11026. assert(producer->getValueKind() == cast->getValueKind());
  11027. cleanups->setSubExpr(producer);
  11028. return cleanups;
  11029. }
  11030. void Sema::ActOnStartStmtExpr() {
  11031. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11032. }
  11033. void Sema::ActOnStmtExprError() {
  11034. // Note that function is also called by TreeTransform when leaving a
  11035. // StmtExpr scope without rebuilding anything.
  11036. DiscardCleanupsInEvaluationContext();
  11037. PopExpressionEvaluationContext();
  11038. }
  11039. ExprResult
  11040. Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
  11041. SourceLocation RPLoc) { // "({..})"
  11042. assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
  11043. CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
  11044. if (hasAnyUnrecoverableErrorsInThisFunction())
  11045. DiscardCleanupsInEvaluationContext();
  11046. assert(!Cleanup.exprNeedsCleanups() &&
  11047. "cleanups within StmtExpr not correctly bound!");
  11048. PopExpressionEvaluationContext();
  11049. // FIXME: there are a variety of strange constraints to enforce here, for
  11050. // example, it is not possible to goto into a stmt expression apparently.
  11051. // More semantic analysis is needed.
  11052. // If there are sub-stmts in the compound stmt, take the type of the last one
  11053. // as the type of the stmtexpr.
  11054. QualType Ty = Context.VoidTy;
  11055. bool StmtExprMayBindToTemp = false;
  11056. if (!Compound->body_empty()) {
  11057. Stmt *LastStmt = Compound->body_back();
  11058. LabelStmt *LastLabelStmt = nullptr;
  11059. // If LastStmt is a label, skip down through into the body.
  11060. while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
  11061. LastLabelStmt = Label;
  11062. LastStmt = Label->getSubStmt();
  11063. }
  11064. if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
  11065. // Do function/array conversion on the last expression, but not
  11066. // lvalue-to-rvalue. However, initialize an unqualified type.
  11067. ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
  11068. if (LastExpr.isInvalid())
  11069. return ExprError();
  11070. Ty = LastExpr.get()->getType().getUnqualifiedType();
  11071. if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
  11072. // In ARC, if the final expression ends in a consume, splice
  11073. // the consume out and bind it later. In the alternate case
  11074. // (when dealing with a retainable type), the result
  11075. // initialization will create a produce. In both cases the
  11076. // result will be +1, and we'll need to balance that out with
  11077. // a bind.
  11078. if (Expr *rebuiltLastStmt
  11079. = maybeRebuildARCConsumingStmt(LastExpr.get())) {
  11080. LastExpr = rebuiltLastStmt;
  11081. } else {
  11082. LastExpr = PerformCopyInitialization(
  11083. InitializedEntity::InitializeResult(LPLoc,
  11084. Ty,
  11085. false),
  11086. SourceLocation(),
  11087. LastExpr);
  11088. }
  11089. if (LastExpr.isInvalid())
  11090. return ExprError();
  11091. if (LastExpr.get() != nullptr) {
  11092. if (!LastLabelStmt)
  11093. Compound->setLastStmt(LastExpr.get());
  11094. else
  11095. LastLabelStmt->setSubStmt(LastExpr.get());
  11096. StmtExprMayBindToTemp = true;
  11097. }
  11098. }
  11099. }
  11100. }
  11101. // FIXME: Check that expression type is complete/non-abstract; statement
  11102. // expressions are not lvalues.
  11103. Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
  11104. if (StmtExprMayBindToTemp)
  11105. return MaybeBindToTemporary(ResStmtExpr);
  11106. return ResStmtExpr;
  11107. }
  11108. ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
  11109. TypeSourceInfo *TInfo,
  11110. ArrayRef<OffsetOfComponent> Components,
  11111. SourceLocation RParenLoc) {
  11112. QualType ArgTy = TInfo->getType();
  11113. bool Dependent = ArgTy->isDependentType();
  11114. SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
  11115. // We must have at least one component that refers to the type, and the first
  11116. // one is known to be a field designator. Verify that the ArgTy represents
  11117. // a struct/union/class.
  11118. if (!Dependent && !ArgTy->isRecordType())
  11119. return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
  11120. << ArgTy << TypeRange);
  11121. // Type must be complete per C99 7.17p3 because a declaring a variable
  11122. // with an incomplete type would be ill-formed.
  11123. if (!Dependent
  11124. && RequireCompleteType(BuiltinLoc, ArgTy,
  11125. diag::err_offsetof_incomplete_type, TypeRange))
  11126. return ExprError();
  11127. bool DidWarnAboutNonPOD = false;
  11128. QualType CurrentType = ArgTy;
  11129. SmallVector<OffsetOfNode, 4> Comps;
  11130. SmallVector<Expr*, 4> Exprs;
  11131. for (const OffsetOfComponent &OC : Components) {
  11132. if (OC.isBrackets) {
  11133. // Offset of an array sub-field. TODO: Should we allow vector elements?
  11134. if (!CurrentType->isDependentType()) {
  11135. const ArrayType *AT = Context.getAsArrayType(CurrentType);
  11136. if(!AT)
  11137. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
  11138. << CurrentType);
  11139. CurrentType = AT->getElementType();
  11140. } else
  11141. CurrentType = Context.DependentTy;
  11142. ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
  11143. if (IdxRval.isInvalid())
  11144. return ExprError();
  11145. Expr *Idx = IdxRval.get();
  11146. // The expression must be an integral expression.
  11147. // FIXME: An integral constant expression?
  11148. if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
  11149. !Idx->getType()->isIntegerType())
  11150. return ExprError(Diag(Idx->getLocStart(),
  11151. diag::err_typecheck_subscript_not_integer)
  11152. << Idx->getSourceRange());
  11153. // Record this array index.
  11154. Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
  11155. Exprs.push_back(Idx);
  11156. continue;
  11157. }
  11158. // Offset of a field.
  11159. if (CurrentType->isDependentType()) {
  11160. // We have the offset of a field, but we can't look into the dependent
  11161. // type. Just record the identifier of the field.
  11162. Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
  11163. CurrentType = Context.DependentTy;
  11164. continue;
  11165. }
  11166. // We need to have a complete type to look into.
  11167. if (RequireCompleteType(OC.LocStart, CurrentType,
  11168. diag::err_offsetof_incomplete_type))
  11169. return ExprError();
  11170. // Look for the designated field.
  11171. const RecordType *RC = CurrentType->getAs<RecordType>();
  11172. if (!RC)
  11173. return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
  11174. << CurrentType);
  11175. RecordDecl *RD = RC->getDecl();
  11176. // C++ [lib.support.types]p5:
  11177. // The macro offsetof accepts a restricted set of type arguments in this
  11178. // International Standard. type shall be a POD structure or a POD union
  11179. // (clause 9).
  11180. // C++11 [support.types]p4:
  11181. // If type is not a standard-layout class (Clause 9), the results are
  11182. // undefined.
  11183. if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  11184. bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
  11185. unsigned DiagID =
  11186. LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
  11187. : diag::ext_offsetof_non_pod_type;
  11188. if (!IsSafe && !DidWarnAboutNonPOD &&
  11189. DiagRuntimeBehavior(BuiltinLoc, nullptr,
  11190. PDiag(DiagID)
  11191. << SourceRange(Components[0].LocStart, OC.LocEnd)
  11192. << CurrentType))
  11193. DidWarnAboutNonPOD = true;
  11194. }
  11195. // Look for the field.
  11196. LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
  11197. LookupQualifiedName(R, RD);
  11198. FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
  11199. IndirectFieldDecl *IndirectMemberDecl = nullptr;
  11200. if (!MemberDecl) {
  11201. if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
  11202. MemberDecl = IndirectMemberDecl->getAnonField();
  11203. }
  11204. if (!MemberDecl)
  11205. return ExprError(Diag(BuiltinLoc, diag::err_no_member)
  11206. << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
  11207. OC.LocEnd));
  11208. // C99 7.17p3:
  11209. // (If the specified member is a bit-field, the behavior is undefined.)
  11210. //
  11211. // We diagnose this as an error.
  11212. if (MemberDecl->isBitField()) {
  11213. Diag(OC.LocEnd, diag::err_offsetof_bitfield)
  11214. << MemberDecl->getDeclName()
  11215. << SourceRange(BuiltinLoc, RParenLoc);
  11216. Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
  11217. return ExprError();
  11218. }
  11219. RecordDecl *Parent = MemberDecl->getParent();
  11220. if (IndirectMemberDecl)
  11221. Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
  11222. // If the member was found in a base class, introduce OffsetOfNodes for
  11223. // the base class indirections.
  11224. CXXBasePaths Paths;
  11225. if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
  11226. Paths)) {
  11227. if (Paths.getDetectedVirtual()) {
  11228. Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
  11229. << MemberDecl->getDeclName()
  11230. << SourceRange(BuiltinLoc, RParenLoc);
  11231. return ExprError();
  11232. }
  11233. CXXBasePath &Path = Paths.front();
  11234. for (const CXXBasePathElement &B : Path)
  11235. Comps.push_back(OffsetOfNode(B.Base));
  11236. }
  11237. if (IndirectMemberDecl) {
  11238. for (auto *FI : IndirectMemberDecl->chain()) {
  11239. assert(isa<FieldDecl>(FI));
  11240. Comps.push_back(OffsetOfNode(OC.LocStart,
  11241. cast<FieldDecl>(FI), OC.LocEnd));
  11242. }
  11243. } else
  11244. Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
  11245. CurrentType = MemberDecl->getType().getNonReferenceType();
  11246. }
  11247. return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
  11248. Comps, Exprs, RParenLoc);
  11249. }
  11250. ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
  11251. SourceLocation BuiltinLoc,
  11252. SourceLocation TypeLoc,
  11253. ParsedType ParsedArgTy,
  11254. ArrayRef<OffsetOfComponent> Components,
  11255. SourceLocation RParenLoc) {
  11256. TypeSourceInfo *ArgTInfo;
  11257. QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
  11258. if (ArgTy.isNull())
  11259. return ExprError();
  11260. if (!ArgTInfo)
  11261. ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
  11262. return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
  11263. }
  11264. ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
  11265. Expr *CondExpr,
  11266. Expr *LHSExpr, Expr *RHSExpr,
  11267. SourceLocation RPLoc) {
  11268. assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
  11269. ExprValueKind VK = VK_RValue;
  11270. ExprObjectKind OK = OK_Ordinary;
  11271. QualType resType;
  11272. bool ValueDependent = false;
  11273. bool CondIsTrue = false;
  11274. if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
  11275. resType = Context.DependentTy;
  11276. ValueDependent = true;
  11277. } else {
  11278. // The conditional expression is required to be a constant expression.
  11279. llvm::APSInt condEval(32);
  11280. ExprResult CondICE
  11281. = VerifyIntegerConstantExpression(CondExpr, &condEval,
  11282. diag::err_typecheck_choose_expr_requires_constant, false);
  11283. if (CondICE.isInvalid())
  11284. return ExprError();
  11285. CondExpr = CondICE.get();
  11286. CondIsTrue = condEval.getZExtValue();
  11287. // If the condition is > zero, then the AST type is the same as the LSHExpr.
  11288. Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
  11289. resType = ActiveExpr->getType();
  11290. ValueDependent = ActiveExpr->isValueDependent();
  11291. VK = ActiveExpr->getValueKind();
  11292. OK = ActiveExpr->getObjectKind();
  11293. }
  11294. return new (Context)
  11295. ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
  11296. CondIsTrue, resType->isDependentType(), ValueDependent);
  11297. }
  11298. //===----------------------------------------------------------------------===//
  11299. // Clang Extensions.
  11300. //===----------------------------------------------------------------------===//
  11301. /// ActOnBlockStart - This callback is invoked when a block literal is started.
  11302. void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
  11303. BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
  11304. if (LangOpts.CPlusPlus) {
  11305. Decl *ManglingContextDecl;
  11306. if (MangleNumberingContext *MCtx =
  11307. getCurrentMangleNumberContext(Block->getDeclContext(),
  11308. ManglingContextDecl)) {
  11309. unsigned ManglingNumber = MCtx->getManglingNumber(Block);
  11310. Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
  11311. }
  11312. }
  11313. PushBlockScope(CurScope, Block);
  11314. CurContext->addDecl(Block);
  11315. if (CurScope)
  11316. PushDeclContext(CurScope, Block);
  11317. else
  11318. CurContext = Block;
  11319. getCurBlock()->HasImplicitReturnType = true;
  11320. // Enter a new evaluation context to insulate the block from any
  11321. // cleanups from the enclosing full-expression.
  11322. PushExpressionEvaluationContext(
  11323. ExpressionEvaluationContext::PotentiallyEvaluated);
  11324. }
  11325. void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
  11326. Scope *CurScope) {
  11327. assert(ParamInfo.getIdentifier() == nullptr &&
  11328. "block-id should have no identifier!");
  11329. assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
  11330. BlockScopeInfo *CurBlock = getCurBlock();
  11331. TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
  11332. QualType T = Sig->getType();
  11333. // FIXME: We should allow unexpanded parameter packs here, but that would,
  11334. // in turn, make the block expression contain unexpanded parameter packs.
  11335. if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
  11336. // Drop the parameters.
  11337. FunctionProtoType::ExtProtoInfo EPI;
  11338. EPI.HasTrailingReturn = false;
  11339. EPI.TypeQuals |= DeclSpec::TQ_const;
  11340. T = Context.getFunctionType(Context.DependentTy, None, EPI);
  11341. Sig = Context.getTrivialTypeSourceInfo(T);
  11342. }
  11343. // GetTypeForDeclarator always produces a function type for a block
  11344. // literal signature. Furthermore, it is always a FunctionProtoType
  11345. // unless the function was written with a typedef.
  11346. assert(T->isFunctionType() &&
  11347. "GetTypeForDeclarator made a non-function block signature");
  11348. // Look for an explicit signature in that function type.
  11349. FunctionProtoTypeLoc ExplicitSignature;
  11350. if ((ExplicitSignature =
  11351. Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
  11352. // Check whether that explicit signature was synthesized by
  11353. // GetTypeForDeclarator. If so, don't save that as part of the
  11354. // written signature.
  11355. if (ExplicitSignature.getLocalRangeBegin() ==
  11356. ExplicitSignature.getLocalRangeEnd()) {
  11357. // This would be much cheaper if we stored TypeLocs instead of
  11358. // TypeSourceInfos.
  11359. TypeLoc Result = ExplicitSignature.getReturnLoc();
  11360. unsigned Size = Result.getFullDataSize();
  11361. Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
  11362. Sig->getTypeLoc().initializeFullCopy(Result, Size);
  11363. ExplicitSignature = FunctionProtoTypeLoc();
  11364. }
  11365. }
  11366. CurBlock->TheDecl->setSignatureAsWritten(Sig);
  11367. CurBlock->FunctionType = T;
  11368. const FunctionType *Fn = T->getAs<FunctionType>();
  11369. QualType RetTy = Fn->getReturnType();
  11370. bool isVariadic =
  11371. (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
  11372. CurBlock->TheDecl->setIsVariadic(isVariadic);
  11373. // Context.DependentTy is used as a placeholder for a missing block
  11374. // return type. TODO: what should we do with declarators like:
  11375. // ^ * { ... }
  11376. // If the answer is "apply template argument deduction"....
  11377. if (RetTy != Context.DependentTy) {
  11378. CurBlock->ReturnType = RetTy;
  11379. CurBlock->TheDecl->setBlockMissingReturnType(false);
  11380. CurBlock->HasImplicitReturnType = false;
  11381. }
  11382. // Push block parameters from the declarator if we had them.
  11383. SmallVector<ParmVarDecl*, 8> Params;
  11384. if (ExplicitSignature) {
  11385. for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
  11386. ParmVarDecl *Param = ExplicitSignature.getParam(I);
  11387. if (Param->getIdentifier() == nullptr &&
  11388. !Param->isImplicit() &&
  11389. !Param->isInvalidDecl() &&
  11390. !getLangOpts().CPlusPlus)
  11391. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  11392. Params.push_back(Param);
  11393. }
  11394. // Fake up parameter variables if we have a typedef, like
  11395. // ^ fntype { ... }
  11396. } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
  11397. for (const auto &I : Fn->param_types()) {
  11398. ParmVarDecl *Param = BuildParmVarDeclForTypedef(
  11399. CurBlock->TheDecl, ParamInfo.getLocStart(), I);
  11400. Params.push_back(Param);
  11401. }
  11402. }
  11403. // Set the parameters on the block decl.
  11404. if (!Params.empty()) {
  11405. CurBlock->TheDecl->setParams(Params);
  11406. CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
  11407. /*CheckParameterNames=*/false);
  11408. }
  11409. // Finally we can process decl attributes.
  11410. ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
  11411. // Put the parameter variables in scope.
  11412. for (auto AI : CurBlock->TheDecl->parameters()) {
  11413. AI->setOwningFunction(CurBlock->TheDecl);
  11414. // If this has an identifier, add it to the scope stack.
  11415. if (AI->getIdentifier()) {
  11416. CheckShadow(CurBlock->TheScope, AI);
  11417. PushOnScopeChains(AI, CurBlock->TheScope);
  11418. }
  11419. }
  11420. }
  11421. /// ActOnBlockError - If there is an error parsing a block, this callback
  11422. /// is invoked to pop the information about the block from the action impl.
  11423. void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
  11424. // Leave the expression-evaluation context.
  11425. DiscardCleanupsInEvaluationContext();
  11426. PopExpressionEvaluationContext();
  11427. // Pop off CurBlock, handle nested blocks.
  11428. PopDeclContext();
  11429. PopFunctionScopeInfo();
  11430. }
  11431. /// ActOnBlockStmtExpr - This is called when the body of a block statement
  11432. /// literal was successfully completed. ^(int x){...}
  11433. ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
  11434. Stmt *Body, Scope *CurScope) {
  11435. // If blocks are disabled, emit an error.
  11436. if (!LangOpts.Blocks)
  11437. Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
  11438. // Leave the expression-evaluation context.
  11439. if (hasAnyUnrecoverableErrorsInThisFunction())
  11440. DiscardCleanupsInEvaluationContext();
  11441. assert(!Cleanup.exprNeedsCleanups() &&
  11442. "cleanups within block not correctly bound!");
  11443. PopExpressionEvaluationContext();
  11444. BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
  11445. if (BSI->HasImplicitReturnType)
  11446. deduceClosureReturnType(*BSI);
  11447. PopDeclContext();
  11448. QualType RetTy = Context.VoidTy;
  11449. if (!BSI->ReturnType.isNull())
  11450. RetTy = BSI->ReturnType;
  11451. bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
  11452. QualType BlockTy;
  11453. // Set the captured variables on the block.
  11454. // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
  11455. SmallVector<BlockDecl::Capture, 4> Captures;
  11456. for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
  11457. if (Cap.isThisCapture())
  11458. continue;
  11459. BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
  11460. Cap.isNested(), Cap.getInitExpr());
  11461. Captures.push_back(NewCap);
  11462. }
  11463. BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
  11464. // If the user wrote a function type in some form, try to use that.
  11465. if (!BSI->FunctionType.isNull()) {
  11466. const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
  11467. FunctionType::ExtInfo Ext = FTy->getExtInfo();
  11468. if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
  11469. // Turn protoless block types into nullary block types.
  11470. if (isa<FunctionNoProtoType>(FTy)) {
  11471. FunctionProtoType::ExtProtoInfo EPI;
  11472. EPI.ExtInfo = Ext;
  11473. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  11474. // Otherwise, if we don't need to change anything about the function type,
  11475. // preserve its sugar structure.
  11476. } else if (FTy->getReturnType() == RetTy &&
  11477. (!NoReturn || FTy->getNoReturnAttr())) {
  11478. BlockTy = BSI->FunctionType;
  11479. // Otherwise, make the minimal modifications to the function type.
  11480. } else {
  11481. const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
  11482. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  11483. EPI.TypeQuals = 0; // FIXME: silently?
  11484. EPI.ExtInfo = Ext;
  11485. BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
  11486. }
  11487. // If we don't have a function type, just build one from nothing.
  11488. } else {
  11489. FunctionProtoType::ExtProtoInfo EPI;
  11490. EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
  11491. BlockTy = Context.getFunctionType(RetTy, None, EPI);
  11492. }
  11493. DiagnoseUnusedParameters(BSI->TheDecl->parameters());
  11494. BlockTy = Context.getBlockPointerType(BlockTy);
  11495. // If needed, diagnose invalid gotos and switches in the block.
  11496. if (getCurFunction()->NeedsScopeChecking() &&
  11497. !PP.isCodeCompletionEnabled())
  11498. DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
  11499. BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
  11500. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11501. DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
  11502. // Try to apply the named return value optimization. We have to check again
  11503. // if we can do this, though, because blocks keep return statements around
  11504. // to deduce an implicit return type.
  11505. if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
  11506. !BSI->TheDecl->isDependentContext())
  11507. computeNRVO(Body, BSI);
  11508. BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
  11509. AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11510. PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
  11511. // If the block isn't obviously global, i.e. it captures anything at
  11512. // all, then we need to do a few things in the surrounding context:
  11513. if (Result->getBlockDecl()->hasCaptures()) {
  11514. // First, this expression has a new cleanup object.
  11515. ExprCleanupObjects.push_back(Result->getBlockDecl());
  11516. Cleanup.setExprNeedsCleanups(true);
  11517. // It also gets a branch-protected scope if any of the captured
  11518. // variables needs destruction.
  11519. for (const auto &CI : Result->getBlockDecl()->captures()) {
  11520. const VarDecl *var = CI.getVariable();
  11521. if (var->getType().isDestructedType() != QualType::DK_none) {
  11522. getCurFunction()->setHasBranchProtectedScope();
  11523. break;
  11524. }
  11525. }
  11526. }
  11527. return Result;
  11528. }
  11529. ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
  11530. SourceLocation RPLoc) {
  11531. TypeSourceInfo *TInfo;
  11532. GetTypeFromParser(Ty, &TInfo);
  11533. return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
  11534. }
  11535. ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
  11536. Expr *E, TypeSourceInfo *TInfo,
  11537. SourceLocation RPLoc) {
  11538. Expr *OrigExpr = E;
  11539. bool IsMS = false;
  11540. // CUDA device code does not support varargs.
  11541. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  11542. if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
  11543. CUDAFunctionTarget T = IdentifyCUDATarget(F);
  11544. if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
  11545. return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
  11546. }
  11547. }
  11548. // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
  11549. // as Microsoft ABI on an actual Microsoft platform, where
  11550. // __builtin_ms_va_list and __builtin_va_list are the same.)
  11551. if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
  11552. Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
  11553. QualType MSVaListType = Context.getBuiltinMSVaListType();
  11554. if (Context.hasSameType(MSVaListType, E->getType())) {
  11555. if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
  11556. return ExprError();
  11557. IsMS = true;
  11558. }
  11559. }
  11560. // Get the va_list type
  11561. QualType VaListType = Context.getBuiltinVaListType();
  11562. if (!IsMS) {
  11563. if (VaListType->isArrayType()) {
  11564. // Deal with implicit array decay; for example, on x86-64,
  11565. // va_list is an array, but it's supposed to decay to
  11566. // a pointer for va_arg.
  11567. VaListType = Context.getArrayDecayedType(VaListType);
  11568. // Make sure the input expression also decays appropriately.
  11569. ExprResult Result = UsualUnaryConversions(E);
  11570. if (Result.isInvalid())
  11571. return ExprError();
  11572. E = Result.get();
  11573. } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
  11574. // If va_list is a record type and we are compiling in C++ mode,
  11575. // check the argument using reference binding.
  11576. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  11577. Context, Context.getLValueReferenceType(VaListType), false);
  11578. ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
  11579. if (Init.isInvalid())
  11580. return ExprError();
  11581. E = Init.getAs<Expr>();
  11582. } else {
  11583. // Otherwise, the va_list argument must be an l-value because
  11584. // it is modified by va_arg.
  11585. if (!E->isTypeDependent() &&
  11586. CheckForModifiableLvalue(E, BuiltinLoc, *this))
  11587. return ExprError();
  11588. }
  11589. }
  11590. if (!IsMS && !E->isTypeDependent() &&
  11591. !Context.hasSameType(VaListType, E->getType()))
  11592. return ExprError(Diag(E->getLocStart(),
  11593. diag::err_first_argument_to_va_arg_not_of_type_va_list)
  11594. << OrigExpr->getType() << E->getSourceRange());
  11595. if (!TInfo->getType()->isDependentType()) {
  11596. if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
  11597. diag::err_second_parameter_to_va_arg_incomplete,
  11598. TInfo->getTypeLoc()))
  11599. return ExprError();
  11600. if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
  11601. TInfo->getType(),
  11602. diag::err_second_parameter_to_va_arg_abstract,
  11603. TInfo->getTypeLoc()))
  11604. return ExprError();
  11605. if (!TInfo->getType().isPODType(Context)) {
  11606. Diag(TInfo->getTypeLoc().getBeginLoc(),
  11607. TInfo->getType()->isObjCLifetimeType()
  11608. ? diag::warn_second_parameter_to_va_arg_ownership_qualified
  11609. : diag::warn_second_parameter_to_va_arg_not_pod)
  11610. << TInfo->getType()
  11611. << TInfo->getTypeLoc().getSourceRange();
  11612. }
  11613. // Check for va_arg where arguments of the given type will be promoted
  11614. // (i.e. this va_arg is guaranteed to have undefined behavior).
  11615. QualType PromoteType;
  11616. if (TInfo->getType()->isPromotableIntegerType()) {
  11617. PromoteType = Context.getPromotedIntegerType(TInfo->getType());
  11618. if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
  11619. PromoteType = QualType();
  11620. }
  11621. if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
  11622. PromoteType = Context.DoubleTy;
  11623. if (!PromoteType.isNull())
  11624. DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
  11625. PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
  11626. << TInfo->getType()
  11627. << PromoteType
  11628. << TInfo->getTypeLoc().getSourceRange());
  11629. }
  11630. QualType T = TInfo->getType().getNonLValueExprType(Context);
  11631. return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
  11632. }
  11633. ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
  11634. // The type of __null will be int or long, depending on the size of
  11635. // pointers on the target.
  11636. QualType Ty;
  11637. unsigned pw = Context.getTargetInfo().getPointerWidth(0);
  11638. if (pw == Context.getTargetInfo().getIntWidth())
  11639. Ty = Context.IntTy;
  11640. else if (pw == Context.getTargetInfo().getLongWidth())
  11641. Ty = Context.LongTy;
  11642. else if (pw == Context.getTargetInfo().getLongLongWidth())
  11643. Ty = Context.LongLongTy;
  11644. else {
  11645. llvm_unreachable("I don't know size of pointer!");
  11646. }
  11647. return new (Context) GNUNullExpr(Ty, TokenLoc);
  11648. }
  11649. bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
  11650. bool Diagnose) {
  11651. if (!getLangOpts().ObjC1)
  11652. return false;
  11653. const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
  11654. if (!PT)
  11655. return false;
  11656. if (!PT->isObjCIdType()) {
  11657. // Check if the destination is the 'NSString' interface.
  11658. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  11659. if (!ID || !ID->getIdentifier()->isStr("NSString"))
  11660. return false;
  11661. }
  11662. // Ignore any parens, implicit casts (should only be
  11663. // array-to-pointer decays), and not-so-opaque values. The last is
  11664. // important for making this trigger for property assignments.
  11665. Expr *SrcExpr = Exp->IgnoreParenImpCasts();
  11666. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
  11667. if (OV->getSourceExpr())
  11668. SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
  11669. StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
  11670. if (!SL || !SL->isAscii())
  11671. return false;
  11672. if (Diagnose) {
  11673. Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
  11674. << FixItHint::CreateInsertion(SL->getLocStart(), "@");
  11675. Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
  11676. }
  11677. return true;
  11678. }
  11679. static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
  11680. const Expr *SrcExpr) {
  11681. if (!DstType->isFunctionPointerType() ||
  11682. !SrcExpr->getType()->isFunctionType())
  11683. return false;
  11684. auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
  11685. if (!DRE)
  11686. return false;
  11687. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  11688. if (!FD)
  11689. return false;
  11690. return !S.checkAddressOfFunctionIsAvailable(FD,
  11691. /*Complain=*/true,
  11692. SrcExpr->getLocStart());
  11693. }
  11694. bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
  11695. SourceLocation Loc,
  11696. QualType DstType, QualType SrcType,
  11697. Expr *SrcExpr, AssignmentAction Action,
  11698. bool *Complained) {
  11699. if (Complained)
  11700. *Complained = false;
  11701. // Decode the result (notice that AST's are still created for extensions).
  11702. bool CheckInferredResultType = false;
  11703. bool isInvalid = false;
  11704. unsigned DiagKind = 0;
  11705. FixItHint Hint;
  11706. ConversionFixItGenerator ConvHints;
  11707. bool MayHaveConvFixit = false;
  11708. bool MayHaveFunctionDiff = false;
  11709. const ObjCInterfaceDecl *IFace = nullptr;
  11710. const ObjCProtocolDecl *PDecl = nullptr;
  11711. switch (ConvTy) {
  11712. case Compatible:
  11713. DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
  11714. return false;
  11715. case PointerToInt:
  11716. DiagKind = diag::ext_typecheck_convert_pointer_int;
  11717. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  11718. MayHaveConvFixit = true;
  11719. break;
  11720. case IntToPointer:
  11721. DiagKind = diag::ext_typecheck_convert_int_pointer;
  11722. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  11723. MayHaveConvFixit = true;
  11724. break;
  11725. case IncompatiblePointer:
  11726. if (Action == AA_Passing_CFAudited)
  11727. DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
  11728. else if (SrcType->isFunctionPointerType() &&
  11729. DstType->isFunctionPointerType())
  11730. DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
  11731. else
  11732. DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
  11733. CheckInferredResultType = DstType->isObjCObjectPointerType() &&
  11734. SrcType->isObjCObjectPointerType();
  11735. if (Hint.isNull() && !CheckInferredResultType) {
  11736. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  11737. }
  11738. else if (CheckInferredResultType) {
  11739. SrcType = SrcType.getUnqualifiedType();
  11740. DstType = DstType.getUnqualifiedType();
  11741. }
  11742. MayHaveConvFixit = true;
  11743. break;
  11744. case IncompatiblePointerSign:
  11745. DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
  11746. break;
  11747. case FunctionVoidPointer:
  11748. DiagKind = diag::ext_typecheck_convert_pointer_void_func;
  11749. break;
  11750. case IncompatiblePointerDiscardsQualifiers: {
  11751. // Perform array-to-pointer decay if necessary.
  11752. if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
  11753. Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
  11754. Qualifiers rhq = DstType->getPointeeType().getQualifiers();
  11755. if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
  11756. DiagKind = diag::err_typecheck_incompatible_address_space;
  11757. break;
  11758. } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
  11759. DiagKind = diag::err_typecheck_incompatible_ownership;
  11760. break;
  11761. }
  11762. llvm_unreachable("unknown error case for discarding qualifiers!");
  11763. // fallthrough
  11764. }
  11765. case CompatiblePointerDiscardsQualifiers:
  11766. // If the qualifiers lost were because we were applying the
  11767. // (deprecated) C++ conversion from a string literal to a char*
  11768. // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
  11769. // Ideally, this check would be performed in
  11770. // checkPointerTypesForAssignment. However, that would require a
  11771. // bit of refactoring (so that the second argument is an
  11772. // expression, rather than a type), which should be done as part
  11773. // of a larger effort to fix checkPointerTypesForAssignment for
  11774. // C++ semantics.
  11775. if (getLangOpts().CPlusPlus &&
  11776. IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
  11777. return false;
  11778. DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
  11779. break;
  11780. case IncompatibleNestedPointerQualifiers:
  11781. DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
  11782. break;
  11783. case IntToBlockPointer:
  11784. DiagKind = diag::err_int_to_block_pointer;
  11785. break;
  11786. case IncompatibleBlockPointer:
  11787. DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
  11788. break;
  11789. case IncompatibleObjCQualifiedId: {
  11790. if (SrcType->isObjCQualifiedIdType()) {
  11791. const ObjCObjectPointerType *srcOPT =
  11792. SrcType->getAs<ObjCObjectPointerType>();
  11793. for (auto *srcProto : srcOPT->quals()) {
  11794. PDecl = srcProto;
  11795. break;
  11796. }
  11797. if (const ObjCInterfaceType *IFaceT =
  11798. DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  11799. IFace = IFaceT->getDecl();
  11800. }
  11801. else if (DstType->isObjCQualifiedIdType()) {
  11802. const ObjCObjectPointerType *dstOPT =
  11803. DstType->getAs<ObjCObjectPointerType>();
  11804. for (auto *dstProto : dstOPT->quals()) {
  11805. PDecl = dstProto;
  11806. break;
  11807. }
  11808. if (const ObjCInterfaceType *IFaceT =
  11809. SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
  11810. IFace = IFaceT->getDecl();
  11811. }
  11812. DiagKind = diag::warn_incompatible_qualified_id;
  11813. break;
  11814. }
  11815. case IncompatibleVectors:
  11816. DiagKind = diag::warn_incompatible_vectors;
  11817. break;
  11818. case IncompatibleObjCWeakRef:
  11819. DiagKind = diag::err_arc_weak_unavailable_assign;
  11820. break;
  11821. case Incompatible:
  11822. if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
  11823. if (Complained)
  11824. *Complained = true;
  11825. return true;
  11826. }
  11827. DiagKind = diag::err_typecheck_convert_incompatible;
  11828. ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
  11829. MayHaveConvFixit = true;
  11830. isInvalid = true;
  11831. MayHaveFunctionDiff = true;
  11832. break;
  11833. }
  11834. QualType FirstType, SecondType;
  11835. switch (Action) {
  11836. case AA_Assigning:
  11837. case AA_Initializing:
  11838. // The destination type comes first.
  11839. FirstType = DstType;
  11840. SecondType = SrcType;
  11841. break;
  11842. case AA_Returning:
  11843. case AA_Passing:
  11844. case AA_Passing_CFAudited:
  11845. case AA_Converting:
  11846. case AA_Sending:
  11847. case AA_Casting:
  11848. // The source type comes first.
  11849. FirstType = SrcType;
  11850. SecondType = DstType;
  11851. break;
  11852. }
  11853. PartialDiagnostic FDiag = PDiag(DiagKind);
  11854. if (Action == AA_Passing_CFAudited)
  11855. FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
  11856. else
  11857. FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
  11858. // If we can fix the conversion, suggest the FixIts.
  11859. assert(ConvHints.isNull() || Hint.isNull());
  11860. if (!ConvHints.isNull()) {
  11861. for (FixItHint &H : ConvHints.Hints)
  11862. FDiag << H;
  11863. } else {
  11864. FDiag << Hint;
  11865. }
  11866. if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
  11867. if (MayHaveFunctionDiff)
  11868. HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
  11869. Diag(Loc, FDiag);
  11870. if (DiagKind == diag::warn_incompatible_qualified_id &&
  11871. PDecl && IFace && !IFace->hasDefinition())
  11872. Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
  11873. << IFace->getName() << PDecl->getName();
  11874. if (SecondType == Context.OverloadTy)
  11875. NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
  11876. FirstType, /*TakingAddress=*/true);
  11877. if (CheckInferredResultType)
  11878. EmitRelatedResultTypeNote(SrcExpr);
  11879. if (Action == AA_Returning && ConvTy == IncompatiblePointer)
  11880. EmitRelatedResultTypeNoteForReturn(DstType);
  11881. if (Complained)
  11882. *Complained = true;
  11883. return isInvalid;
  11884. }
  11885. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  11886. llvm::APSInt *Result) {
  11887. class SimpleICEDiagnoser : public VerifyICEDiagnoser {
  11888. public:
  11889. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  11890. S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
  11891. }
  11892. } Diagnoser;
  11893. return VerifyIntegerConstantExpression(E, Result, Diagnoser);
  11894. }
  11895. ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
  11896. llvm::APSInt *Result,
  11897. unsigned DiagID,
  11898. bool AllowFold) {
  11899. class IDDiagnoser : public VerifyICEDiagnoser {
  11900. unsigned DiagID;
  11901. public:
  11902. IDDiagnoser(unsigned DiagID)
  11903. : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
  11904. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  11905. S.Diag(Loc, DiagID) << SR;
  11906. }
  11907. } Diagnoser(DiagID);
  11908. return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
  11909. }
  11910. void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
  11911. SourceRange SR) {
  11912. S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
  11913. }
  11914. ExprResult
  11915. Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
  11916. VerifyICEDiagnoser &Diagnoser,
  11917. bool AllowFold) {
  11918. SourceLocation DiagLoc = E->getLocStart();
  11919. if (getLangOpts().CPlusPlus11) {
  11920. // C++11 [expr.const]p5:
  11921. // If an expression of literal class type is used in a context where an
  11922. // integral constant expression is required, then that class type shall
  11923. // have a single non-explicit conversion function to an integral or
  11924. // unscoped enumeration type
  11925. ExprResult Converted;
  11926. class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
  11927. public:
  11928. CXX11ConvertDiagnoser(bool Silent)
  11929. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
  11930. Silent, true) {}
  11931. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  11932. QualType T) override {
  11933. return S.Diag(Loc, diag::err_ice_not_integral) << T;
  11934. }
  11935. SemaDiagnosticBuilder diagnoseIncomplete(
  11936. Sema &S, SourceLocation Loc, QualType T) override {
  11937. return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
  11938. }
  11939. SemaDiagnosticBuilder diagnoseExplicitConv(
  11940. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  11941. return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
  11942. }
  11943. SemaDiagnosticBuilder noteExplicitConv(
  11944. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  11945. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  11946. << ConvTy->isEnumeralType() << ConvTy;
  11947. }
  11948. SemaDiagnosticBuilder diagnoseAmbiguous(
  11949. Sema &S, SourceLocation Loc, QualType T) override {
  11950. return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
  11951. }
  11952. SemaDiagnosticBuilder noteAmbiguous(
  11953. Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
  11954. return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
  11955. << ConvTy->isEnumeralType() << ConvTy;
  11956. }
  11957. SemaDiagnosticBuilder diagnoseConversion(
  11958. Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
  11959. llvm_unreachable("conversion functions are permitted");
  11960. }
  11961. } ConvertDiagnoser(Diagnoser.Suppress);
  11962. Converted = PerformContextualImplicitConversion(DiagLoc, E,
  11963. ConvertDiagnoser);
  11964. if (Converted.isInvalid())
  11965. return Converted;
  11966. E = Converted.get();
  11967. if (!E->getType()->isIntegralOrUnscopedEnumerationType())
  11968. return ExprError();
  11969. } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
  11970. // An ICE must be of integral or unscoped enumeration type.
  11971. if (!Diagnoser.Suppress)
  11972. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  11973. return ExprError();
  11974. }
  11975. // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
  11976. // in the non-ICE case.
  11977. if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
  11978. if (Result)
  11979. *Result = E->EvaluateKnownConstInt(Context);
  11980. return E;
  11981. }
  11982. Expr::EvalResult EvalResult;
  11983. SmallVector<PartialDiagnosticAt, 8> Notes;
  11984. EvalResult.Diag = &Notes;
  11985. // Try to evaluate the expression, and produce diagnostics explaining why it's
  11986. // not a constant expression as a side-effect.
  11987. bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
  11988. EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
  11989. // In C++11, we can rely on diagnostics being produced for any expression
  11990. // which is not a constant expression. If no diagnostics were produced, then
  11991. // this is a constant expression.
  11992. if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
  11993. if (Result)
  11994. *Result = EvalResult.Val.getInt();
  11995. return E;
  11996. }
  11997. // If our only note is the usual "invalid subexpression" note, just point
  11998. // the caret at its location rather than producing an essentially
  11999. // redundant note.
  12000. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  12001. diag::note_invalid_subexpr_in_const_expr) {
  12002. DiagLoc = Notes[0].first;
  12003. Notes.clear();
  12004. }
  12005. if (!Folded || !AllowFold) {
  12006. if (!Diagnoser.Suppress) {
  12007. Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
  12008. for (const PartialDiagnosticAt &Note : Notes)
  12009. Diag(Note.first, Note.second);
  12010. }
  12011. return ExprError();
  12012. }
  12013. Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
  12014. for (const PartialDiagnosticAt &Note : Notes)
  12015. Diag(Note.first, Note.second);
  12016. if (Result)
  12017. *Result = EvalResult.Val.getInt();
  12018. return E;
  12019. }
  12020. namespace {
  12021. // Handle the case where we conclude a expression which we speculatively
  12022. // considered to be unevaluated is actually evaluated.
  12023. class TransformToPE : public TreeTransform<TransformToPE> {
  12024. typedef TreeTransform<TransformToPE> BaseTransform;
  12025. public:
  12026. TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
  12027. // Make sure we redo semantic analysis
  12028. bool AlwaysRebuild() { return true; }
  12029. // Make sure we handle LabelStmts correctly.
  12030. // FIXME: This does the right thing, but maybe we need a more general
  12031. // fix to TreeTransform?
  12032. StmtResult TransformLabelStmt(LabelStmt *S) {
  12033. S->getDecl()->setStmt(nullptr);
  12034. return BaseTransform::TransformLabelStmt(S);
  12035. }
  12036. // We need to special-case DeclRefExprs referring to FieldDecls which
  12037. // are not part of a member pointer formation; normal TreeTransforming
  12038. // doesn't catch this case because of the way we represent them in the AST.
  12039. // FIXME: This is a bit ugly; is it really the best way to handle this
  12040. // case?
  12041. //
  12042. // Error on DeclRefExprs referring to FieldDecls.
  12043. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  12044. if (isa<FieldDecl>(E->getDecl()) &&
  12045. !SemaRef.isUnevaluatedContext())
  12046. return SemaRef.Diag(E->getLocation(),
  12047. diag::err_invalid_non_static_member_use)
  12048. << E->getDecl() << E->getSourceRange();
  12049. return BaseTransform::TransformDeclRefExpr(E);
  12050. }
  12051. // Exception: filter out member pointer formation
  12052. ExprResult TransformUnaryOperator(UnaryOperator *E) {
  12053. if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
  12054. return E;
  12055. return BaseTransform::TransformUnaryOperator(E);
  12056. }
  12057. ExprResult TransformLambdaExpr(LambdaExpr *E) {
  12058. // Lambdas never need to be transformed.
  12059. return E;
  12060. }
  12061. };
  12062. }
  12063. ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
  12064. assert(isUnevaluatedContext() &&
  12065. "Should only transform unevaluated expressions");
  12066. ExprEvalContexts.back().Context =
  12067. ExprEvalContexts[ExprEvalContexts.size()-2].Context;
  12068. if (isUnevaluatedContext())
  12069. return E;
  12070. return TransformToPE(*this).TransformExpr(E);
  12071. }
  12072. void
  12073. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  12074. Decl *LambdaContextDecl,
  12075. bool IsDecltype) {
  12076. ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
  12077. LambdaContextDecl, IsDecltype);
  12078. Cleanup.reset();
  12079. if (!MaybeODRUseExprs.empty())
  12080. std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
  12081. }
  12082. void
  12083. Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
  12084. ReuseLambdaContextDecl_t,
  12085. bool IsDecltype) {
  12086. Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
  12087. PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
  12088. }
  12089. void Sema::PopExpressionEvaluationContext() {
  12090. ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
  12091. unsigned NumTypos = Rec.NumTypos;
  12092. if (!Rec.Lambdas.empty()) {
  12093. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  12094. unsigned D;
  12095. if (Rec.isUnevaluated()) {
  12096. // C++11 [expr.prim.lambda]p2:
  12097. // A lambda-expression shall not appear in an unevaluated operand
  12098. // (Clause 5).
  12099. D = diag::err_lambda_unevaluated_operand;
  12100. } else {
  12101. // C++1y [expr.const]p2:
  12102. // A conditional-expression e is a core constant expression unless the
  12103. // evaluation of e, following the rules of the abstract machine, would
  12104. // evaluate [...] a lambda-expression.
  12105. D = diag::err_lambda_in_constant_expression;
  12106. }
  12107. // C++1z allows lambda expressions as core constant expressions.
  12108. // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
  12109. // 1607) from appearing within template-arguments and array-bounds that
  12110. // are part of function-signatures. Be mindful that P0315 (Lambdas in
  12111. // unevaluated contexts) might lift some of these restrictions in a
  12112. // future version.
  12113. if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
  12114. for (const auto *L : Rec.Lambdas)
  12115. Diag(L->getLocStart(), D);
  12116. } else {
  12117. // Mark the capture expressions odr-used. This was deferred
  12118. // during lambda expression creation.
  12119. for (auto *Lambda : Rec.Lambdas) {
  12120. for (auto *C : Lambda->capture_inits())
  12121. MarkDeclarationsReferencedInExpr(C);
  12122. }
  12123. }
  12124. }
  12125. // When are coming out of an unevaluated context, clear out any
  12126. // temporaries that we may have created as part of the evaluation of
  12127. // the expression in that context: they aren't relevant because they
  12128. // will never be constructed.
  12129. if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
  12130. ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
  12131. ExprCleanupObjects.end());
  12132. Cleanup = Rec.ParentCleanup;
  12133. CleanupVarDeclMarking();
  12134. std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
  12135. // Otherwise, merge the contexts together.
  12136. } else {
  12137. Cleanup.mergeFrom(Rec.ParentCleanup);
  12138. MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
  12139. Rec.SavedMaybeODRUseExprs.end());
  12140. }
  12141. // Pop the current expression evaluation context off the stack.
  12142. ExprEvalContexts.pop_back();
  12143. if (!ExprEvalContexts.empty())
  12144. ExprEvalContexts.back().NumTypos += NumTypos;
  12145. else
  12146. assert(NumTypos == 0 && "There are outstanding typos after popping the "
  12147. "last ExpressionEvaluationContextRecord");
  12148. }
  12149. void Sema::DiscardCleanupsInEvaluationContext() {
  12150. ExprCleanupObjects.erase(
  12151. ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
  12152. ExprCleanupObjects.end());
  12153. Cleanup.reset();
  12154. MaybeODRUseExprs.clear();
  12155. }
  12156. ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
  12157. if (!E->getType()->isVariablyModifiedType())
  12158. return E;
  12159. return TransformToPotentiallyEvaluated(E);
  12160. }
  12161. /// Are we within a context in which some evaluation could be performed (be it
  12162. /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
  12163. /// captured by C++'s idea of an "unevaluated context".
  12164. static bool isEvaluatableContext(Sema &SemaRef) {
  12165. switch (SemaRef.ExprEvalContexts.back().Context) {
  12166. case Sema::ExpressionEvaluationContext::Unevaluated:
  12167. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  12168. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  12169. // Expressions in this context are never evaluated.
  12170. return false;
  12171. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  12172. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  12173. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  12174. // Expressions in this context could be evaluated.
  12175. return true;
  12176. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  12177. // Referenced declarations will only be used if the construct in the
  12178. // containing expression is used, at which point we'll be given another
  12179. // turn to mark them.
  12180. return false;
  12181. }
  12182. llvm_unreachable("Invalid context");
  12183. }
  12184. /// Are we within a context in which references to resolved functions or to
  12185. /// variables result in odr-use?
  12186. static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
  12187. // An expression in a template is not really an expression until it's been
  12188. // instantiated, so it doesn't trigger odr-use.
  12189. if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
  12190. return false;
  12191. switch (SemaRef.ExprEvalContexts.back().Context) {
  12192. case Sema::ExpressionEvaluationContext::Unevaluated:
  12193. case Sema::ExpressionEvaluationContext::UnevaluatedList:
  12194. case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
  12195. case Sema::ExpressionEvaluationContext::DiscardedStatement:
  12196. return false;
  12197. case Sema::ExpressionEvaluationContext::ConstantEvaluated:
  12198. case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
  12199. return true;
  12200. case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  12201. return false;
  12202. }
  12203. llvm_unreachable("Invalid context");
  12204. }
  12205. static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
  12206. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
  12207. return Func->isConstexpr() &&
  12208. (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
  12209. }
  12210. /// \brief Mark a function referenced, and check whether it is odr-used
  12211. /// (C++ [basic.def.odr]p2, C99 6.9p3)
  12212. void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
  12213. bool MightBeOdrUse) {
  12214. assert(Func && "No function?");
  12215. Func->setReferenced();
  12216. // C++11 [basic.def.odr]p3:
  12217. // A function whose name appears as a potentially-evaluated expression is
  12218. // odr-used if it is the unique lookup result or the selected member of a
  12219. // set of overloaded functions [...].
  12220. //
  12221. // We (incorrectly) mark overload resolution as an unevaluated context, so we
  12222. // can just check that here.
  12223. bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
  12224. // Determine whether we require a function definition to exist, per
  12225. // C++11 [temp.inst]p3:
  12226. // Unless a function template specialization has been explicitly
  12227. // instantiated or explicitly specialized, the function template
  12228. // specialization is implicitly instantiated when the specialization is
  12229. // referenced in a context that requires a function definition to exist.
  12230. //
  12231. // That is either when this is an odr-use, or when a usage of a constexpr
  12232. // function occurs within an evaluatable context.
  12233. bool NeedDefinition =
  12234. OdrUse || (isEvaluatableContext(*this) &&
  12235. isImplicitlyDefinableConstexprFunction(Func));
  12236. // C++14 [temp.expl.spec]p6:
  12237. // If a template [...] is explicitly specialized then that specialization
  12238. // shall be declared before the first use of that specialization that would
  12239. // cause an implicit instantiation to take place, in every translation unit
  12240. // in which such a use occurs
  12241. if (NeedDefinition &&
  12242. (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
  12243. Func->getMemberSpecializationInfo()))
  12244. checkSpecializationVisibility(Loc, Func);
  12245. // C++14 [except.spec]p17:
  12246. // An exception-specification is considered to be needed when:
  12247. // - the function is odr-used or, if it appears in an unevaluated operand,
  12248. // would be odr-used if the expression were potentially-evaluated;
  12249. //
  12250. // Note, we do this even if MightBeOdrUse is false. That indicates that the
  12251. // function is a pure virtual function we're calling, and in that case the
  12252. // function was selected by overload resolution and we need to resolve its
  12253. // exception specification for a different reason.
  12254. const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
  12255. if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
  12256. ResolveExceptionSpec(Loc, FPT);
  12257. // If we don't need to mark the function as used, and we don't need to
  12258. // try to provide a definition, there's nothing more to do.
  12259. if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
  12260. (!NeedDefinition || Func->getBody()))
  12261. return;
  12262. // Note that this declaration has been used.
  12263. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
  12264. Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
  12265. if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
  12266. if (Constructor->isDefaultConstructor()) {
  12267. if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
  12268. return;
  12269. DefineImplicitDefaultConstructor(Loc, Constructor);
  12270. } else if (Constructor->isCopyConstructor()) {
  12271. DefineImplicitCopyConstructor(Loc, Constructor);
  12272. } else if (Constructor->isMoveConstructor()) {
  12273. DefineImplicitMoveConstructor(Loc, Constructor);
  12274. }
  12275. } else if (Constructor->getInheritedConstructor()) {
  12276. DefineInheritingConstructor(Loc, Constructor);
  12277. }
  12278. } else if (CXXDestructorDecl *Destructor =
  12279. dyn_cast<CXXDestructorDecl>(Func)) {
  12280. Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
  12281. if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
  12282. if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
  12283. return;
  12284. DefineImplicitDestructor(Loc, Destructor);
  12285. }
  12286. if (Destructor->isVirtual() && getLangOpts().AppleKext)
  12287. MarkVTableUsed(Loc, Destructor->getParent());
  12288. } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
  12289. if (MethodDecl->isOverloadedOperator() &&
  12290. MethodDecl->getOverloadedOperator() == OO_Equal) {
  12291. MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
  12292. if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
  12293. if (MethodDecl->isCopyAssignmentOperator())
  12294. DefineImplicitCopyAssignment(Loc, MethodDecl);
  12295. else if (MethodDecl->isMoveAssignmentOperator())
  12296. DefineImplicitMoveAssignment(Loc, MethodDecl);
  12297. }
  12298. } else if (isa<CXXConversionDecl>(MethodDecl) &&
  12299. MethodDecl->getParent()->isLambda()) {
  12300. CXXConversionDecl *Conversion =
  12301. cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
  12302. if (Conversion->isLambdaToBlockPointerConversion())
  12303. DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
  12304. else
  12305. DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
  12306. } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
  12307. MarkVTableUsed(Loc, MethodDecl->getParent());
  12308. }
  12309. // Recursive functions should be marked when used from another function.
  12310. // FIXME: Is this really right?
  12311. if (CurContext == Func) return;
  12312. // Implicit instantiation of function templates and member functions of
  12313. // class templates.
  12314. if (Func->isImplicitlyInstantiable()) {
  12315. TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
  12316. SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
  12317. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  12318. if (FirstInstantiation) {
  12319. PointOfInstantiation = Loc;
  12320. Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  12321. } else if (TSK != TSK_ImplicitInstantiation) {
  12322. // Use the point of use as the point of instantiation, instead of the
  12323. // point of explicit instantiation (which we track as the actual point of
  12324. // instantiation). This gives better backtraces in diagnostics.
  12325. PointOfInstantiation = Loc;
  12326. }
  12327. if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
  12328. Func->isConstexpr()) {
  12329. if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
  12330. cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
  12331. CodeSynthesisContexts.size())
  12332. PendingLocalImplicitInstantiations.push_back(
  12333. std::make_pair(Func, PointOfInstantiation));
  12334. else if (Func->isConstexpr())
  12335. // Do not defer instantiations of constexpr functions, to avoid the
  12336. // expression evaluator needing to call back into Sema if it sees a
  12337. // call to such a function.
  12338. InstantiateFunctionDefinition(PointOfInstantiation, Func);
  12339. else {
  12340. Func->setInstantiationIsPending(true);
  12341. PendingInstantiations.push_back(std::make_pair(Func,
  12342. PointOfInstantiation));
  12343. // Notify the consumer that a function was implicitly instantiated.
  12344. Consumer.HandleCXXImplicitFunctionInstantiation(Func);
  12345. }
  12346. }
  12347. } else {
  12348. // Walk redefinitions, as some of them may be instantiable.
  12349. for (auto i : Func->redecls()) {
  12350. if (!i->isUsed(false) && i->isImplicitlyInstantiable())
  12351. MarkFunctionReferenced(Loc, i, OdrUse);
  12352. }
  12353. }
  12354. if (!OdrUse) return;
  12355. // Keep track of used but undefined functions.
  12356. if (!Func->isDefined()) {
  12357. if (mightHaveNonExternalLinkage(Func))
  12358. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12359. else if (Func->getMostRecentDecl()->isInlined() &&
  12360. !LangOpts.GNUInline &&
  12361. !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
  12362. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12363. else if (isExternalWithNoLinkageType(Func))
  12364. UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
  12365. }
  12366. Func->markUsed(Context);
  12367. }
  12368. static void
  12369. diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
  12370. ValueDecl *var, DeclContext *DC) {
  12371. DeclContext *VarDC = var->getDeclContext();
  12372. // If the parameter still belongs to the translation unit, then
  12373. // we're actually just using one parameter in the declaration of
  12374. // the next.
  12375. if (isa<ParmVarDecl>(var) &&
  12376. isa<TranslationUnitDecl>(VarDC))
  12377. return;
  12378. // For C code, don't diagnose about capture if we're not actually in code
  12379. // right now; it's impossible to write a non-constant expression outside of
  12380. // function context, so we'll get other (more useful) diagnostics later.
  12381. //
  12382. // For C++, things get a bit more nasty... it would be nice to suppress this
  12383. // diagnostic for certain cases like using a local variable in an array bound
  12384. // for a member of a local class, but the correct predicate is not obvious.
  12385. if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
  12386. return;
  12387. unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
  12388. unsigned ContextKind = 3; // unknown
  12389. if (isa<CXXMethodDecl>(VarDC) &&
  12390. cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
  12391. ContextKind = 2;
  12392. } else if (isa<FunctionDecl>(VarDC)) {
  12393. ContextKind = 0;
  12394. } else if (isa<BlockDecl>(VarDC)) {
  12395. ContextKind = 1;
  12396. }
  12397. S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
  12398. << var << ValueKind << ContextKind << VarDC;
  12399. S.Diag(var->getLocation(), diag::note_entity_declared_at)
  12400. << var;
  12401. // FIXME: Add additional diagnostic info about class etc. which prevents
  12402. // capture.
  12403. }
  12404. static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
  12405. bool &SubCapturesAreNested,
  12406. QualType &CaptureType,
  12407. QualType &DeclRefType) {
  12408. // Check whether we've already captured it.
  12409. if (CSI->CaptureMap.count(Var)) {
  12410. // If we found a capture, any subcaptures are nested.
  12411. SubCapturesAreNested = true;
  12412. // Retrieve the capture type for this variable.
  12413. CaptureType = CSI->getCapture(Var).getCaptureType();
  12414. // Compute the type of an expression that refers to this variable.
  12415. DeclRefType = CaptureType.getNonReferenceType();
  12416. // Similarly to mutable captures in lambda, all the OpenMP captures by copy
  12417. // are mutable in the sense that user can change their value - they are
  12418. // private instances of the captured declarations.
  12419. const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
  12420. if (Cap.isCopyCapture() &&
  12421. !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
  12422. !(isa<CapturedRegionScopeInfo>(CSI) &&
  12423. cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
  12424. DeclRefType.addConst();
  12425. return true;
  12426. }
  12427. return false;
  12428. }
  12429. // Only block literals, captured statements, and lambda expressions can
  12430. // capture; other scopes don't work.
  12431. static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
  12432. SourceLocation Loc,
  12433. const bool Diagnose, Sema &S) {
  12434. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
  12435. return getLambdaAwareParentOfDeclContext(DC);
  12436. else if (Var->hasLocalStorage()) {
  12437. if (Diagnose)
  12438. diagnoseUncapturableValueReference(S, Loc, Var, DC);
  12439. }
  12440. return nullptr;
  12441. }
  12442. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  12443. // certain types of variables (unnamed, variably modified types etc.)
  12444. // so check for eligibility.
  12445. static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
  12446. SourceLocation Loc,
  12447. const bool Diagnose, Sema &S) {
  12448. bool IsBlock = isa<BlockScopeInfo>(CSI);
  12449. bool IsLambda = isa<LambdaScopeInfo>(CSI);
  12450. // Lambdas are not allowed to capture unnamed variables
  12451. // (e.g. anonymous unions).
  12452. // FIXME: The C++11 rule don't actually state this explicitly, but I'm
  12453. // assuming that's the intent.
  12454. if (IsLambda && !Var->getDeclName()) {
  12455. if (Diagnose) {
  12456. S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
  12457. S.Diag(Var->getLocation(), diag::note_declared_at);
  12458. }
  12459. return false;
  12460. }
  12461. // Prohibit variably-modified types in blocks; they're difficult to deal with.
  12462. if (Var->getType()->isVariablyModifiedType() && IsBlock) {
  12463. if (Diagnose) {
  12464. S.Diag(Loc, diag::err_ref_vm_type);
  12465. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12466. << Var->getDeclName();
  12467. }
  12468. return false;
  12469. }
  12470. // Prohibit structs with flexible array members too.
  12471. // We cannot capture what is in the tail end of the struct.
  12472. if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
  12473. if (VTTy->getDecl()->hasFlexibleArrayMember()) {
  12474. if (Diagnose) {
  12475. if (IsBlock)
  12476. S.Diag(Loc, diag::err_ref_flexarray_type);
  12477. else
  12478. S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
  12479. << Var->getDeclName();
  12480. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12481. << Var->getDeclName();
  12482. }
  12483. return false;
  12484. }
  12485. }
  12486. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  12487. // Lambdas and captured statements are not allowed to capture __block
  12488. // variables; they don't support the expected semantics.
  12489. if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
  12490. if (Diagnose) {
  12491. S.Diag(Loc, diag::err_capture_block_variable)
  12492. << Var->getDeclName() << !IsLambda;
  12493. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12494. << Var->getDeclName();
  12495. }
  12496. return false;
  12497. }
  12498. // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
  12499. if (S.getLangOpts().OpenCL && IsBlock &&
  12500. Var->getType()->isBlockPointerType()) {
  12501. if (Diagnose)
  12502. S.Diag(Loc, diag::err_opencl_block_ref_block);
  12503. return false;
  12504. }
  12505. return true;
  12506. }
  12507. // Returns true if the capture by block was successful.
  12508. static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
  12509. SourceLocation Loc,
  12510. const bool BuildAndDiagnose,
  12511. QualType &CaptureType,
  12512. QualType &DeclRefType,
  12513. const bool Nested,
  12514. Sema &S) {
  12515. Expr *CopyExpr = nullptr;
  12516. bool ByRef = false;
  12517. // Blocks are not allowed to capture arrays.
  12518. if (CaptureType->isArrayType()) {
  12519. if (BuildAndDiagnose) {
  12520. S.Diag(Loc, diag::err_ref_array_type);
  12521. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12522. << Var->getDeclName();
  12523. }
  12524. return false;
  12525. }
  12526. // Forbid the block-capture of autoreleasing variables.
  12527. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  12528. if (BuildAndDiagnose) {
  12529. S.Diag(Loc, diag::err_arc_autoreleasing_capture)
  12530. << /*block*/ 0;
  12531. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12532. << Var->getDeclName();
  12533. }
  12534. return false;
  12535. }
  12536. // Warn about implicitly autoreleasing indirect parameters captured by blocks.
  12537. if (const auto *PT = CaptureType->getAs<PointerType>()) {
  12538. // This function finds out whether there is an AttributedType of kind
  12539. // attr_objc_ownership in Ty. The existence of AttributedType of kind
  12540. // attr_objc_ownership implies __autoreleasing was explicitly specified
  12541. // rather than being added implicitly by the compiler.
  12542. auto IsObjCOwnershipAttributedType = [](QualType Ty) {
  12543. while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
  12544. if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
  12545. return true;
  12546. // Peel off AttributedTypes that are not of kind objc_ownership.
  12547. Ty = AttrTy->getModifiedType();
  12548. }
  12549. return false;
  12550. };
  12551. QualType PointeeTy = PT->getPointeeType();
  12552. if (PointeeTy->getAs<ObjCObjectPointerType>() &&
  12553. PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
  12554. !IsObjCOwnershipAttributedType(PointeeTy)) {
  12555. if (BuildAndDiagnose) {
  12556. SourceLocation VarLoc = Var->getLocation();
  12557. S.Diag(Loc, diag::warn_block_capture_autoreleasing);
  12558. {
  12559. auto AddAutoreleaseNote =
  12560. S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
  12561. // Provide a fix-it for the '__autoreleasing' keyword at the
  12562. // appropriate location in the variable's type.
  12563. if (const auto *TSI = Var->getTypeSourceInfo()) {
  12564. PointerTypeLoc PTL =
  12565. TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
  12566. if (PTL) {
  12567. SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
  12568. Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
  12569. S.getLangOpts());
  12570. if (Loc.isValid()) {
  12571. StringRef CharAtLoc = Lexer::getSourceText(
  12572. CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
  12573. S.getSourceManager(), S.getLangOpts());
  12574. AddAutoreleaseNote << FixItHint::CreateInsertion(
  12575. Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
  12576. ? " __autoreleasing "
  12577. : " __autoreleasing");
  12578. }
  12579. }
  12580. }
  12581. }
  12582. S.Diag(VarLoc, diag::note_declare_parameter_strong);
  12583. }
  12584. }
  12585. }
  12586. const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
  12587. if (HasBlocksAttr || CaptureType->isReferenceType() ||
  12588. (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
  12589. // Block capture by reference does not change the capture or
  12590. // declaration reference types.
  12591. ByRef = true;
  12592. } else {
  12593. // Block capture by copy introduces 'const'.
  12594. CaptureType = CaptureType.getNonReferenceType().withConst();
  12595. DeclRefType = CaptureType;
  12596. if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
  12597. if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
  12598. // The capture logic needs the destructor, so make sure we mark it.
  12599. // Usually this is unnecessary because most local variables have
  12600. // their destructors marked at declaration time, but parameters are
  12601. // an exception because it's technically only the call site that
  12602. // actually requires the destructor.
  12603. if (isa<ParmVarDecl>(Var))
  12604. S.FinalizeVarWithDestructor(Var, Record);
  12605. // Enter a new evaluation context to insulate the copy
  12606. // full-expression.
  12607. EnterExpressionEvaluationContext scope(
  12608. S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  12609. // According to the blocks spec, the capture of a variable from
  12610. // the stack requires a const copy constructor. This is not true
  12611. // of the copy/move done to move a __block variable to the heap.
  12612. Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
  12613. DeclRefType.withConst(),
  12614. VK_LValue, Loc);
  12615. ExprResult Result
  12616. = S.PerformCopyInitialization(
  12617. InitializedEntity::InitializeBlock(Var->getLocation(),
  12618. CaptureType, false),
  12619. Loc, DeclRef);
  12620. // Build a full-expression copy expression if initialization
  12621. // succeeded and used a non-trivial constructor. Recover from
  12622. // errors by pretending that the copy isn't necessary.
  12623. if (!Result.isInvalid() &&
  12624. !cast<CXXConstructExpr>(Result.get())->getConstructor()
  12625. ->isTrivial()) {
  12626. Result = S.MaybeCreateExprWithCleanups(Result);
  12627. CopyExpr = Result.get();
  12628. }
  12629. }
  12630. }
  12631. }
  12632. // Actually capture the variable.
  12633. if (BuildAndDiagnose)
  12634. BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
  12635. SourceLocation(), CaptureType, CopyExpr);
  12636. return true;
  12637. }
  12638. /// \brief Capture the given variable in the captured region.
  12639. static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
  12640. VarDecl *Var,
  12641. SourceLocation Loc,
  12642. const bool BuildAndDiagnose,
  12643. QualType &CaptureType,
  12644. QualType &DeclRefType,
  12645. const bool RefersToCapturedVariable,
  12646. Sema &S) {
  12647. // By default, capture variables by reference.
  12648. bool ByRef = true;
  12649. // Using an LValue reference type is consistent with Lambdas (see below).
  12650. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
  12651. if (S.IsOpenMPCapturedDecl(Var)) {
  12652. bool HasConst = DeclRefType.isConstQualified();
  12653. DeclRefType = DeclRefType.getUnqualifiedType();
  12654. // Don't lose diagnostics about assignments to const.
  12655. if (HasConst)
  12656. DeclRefType.addConst();
  12657. }
  12658. ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
  12659. }
  12660. if (ByRef)
  12661. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  12662. else
  12663. CaptureType = DeclRefType;
  12664. Expr *CopyExpr = nullptr;
  12665. if (BuildAndDiagnose) {
  12666. // The current implementation assumes that all variables are captured
  12667. // by references. Since there is no capture by copy, no expression
  12668. // evaluation will be needed.
  12669. RecordDecl *RD = RSI->TheRecordDecl;
  12670. FieldDecl *Field
  12671. = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
  12672. S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
  12673. nullptr, false, ICIS_NoInit);
  12674. Field->setImplicit(true);
  12675. Field->setAccess(AS_private);
  12676. RD->addDecl(Field);
  12677. if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
  12678. S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
  12679. CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
  12680. DeclRefType, VK_LValue, Loc);
  12681. Var->setReferenced(true);
  12682. Var->markUsed(S.Context);
  12683. }
  12684. // Actually capture the variable.
  12685. if (BuildAndDiagnose)
  12686. RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
  12687. SourceLocation(), CaptureType, CopyExpr);
  12688. return true;
  12689. }
  12690. /// \brief Create a field within the lambda class for the variable
  12691. /// being captured.
  12692. static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
  12693. QualType FieldType, QualType DeclRefType,
  12694. SourceLocation Loc,
  12695. bool RefersToCapturedVariable) {
  12696. CXXRecordDecl *Lambda = LSI->Lambda;
  12697. // Build the non-static data member.
  12698. FieldDecl *Field
  12699. = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
  12700. S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
  12701. nullptr, false, ICIS_NoInit);
  12702. Field->setImplicit(true);
  12703. Field->setAccess(AS_private);
  12704. Lambda->addDecl(Field);
  12705. }
  12706. /// \brief Capture the given variable in the lambda.
  12707. static bool captureInLambda(LambdaScopeInfo *LSI,
  12708. VarDecl *Var,
  12709. SourceLocation Loc,
  12710. const bool BuildAndDiagnose,
  12711. QualType &CaptureType,
  12712. QualType &DeclRefType,
  12713. const bool RefersToCapturedVariable,
  12714. const Sema::TryCaptureKind Kind,
  12715. SourceLocation EllipsisLoc,
  12716. const bool IsTopScope,
  12717. Sema &S) {
  12718. // Determine whether we are capturing by reference or by value.
  12719. bool ByRef = false;
  12720. if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
  12721. ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
  12722. } else {
  12723. ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
  12724. }
  12725. // Compute the type of the field that will capture this variable.
  12726. if (ByRef) {
  12727. // C++11 [expr.prim.lambda]p15:
  12728. // An entity is captured by reference if it is implicitly or
  12729. // explicitly captured but not captured by copy. It is
  12730. // unspecified whether additional unnamed non-static data
  12731. // members are declared in the closure type for entities
  12732. // captured by reference.
  12733. //
  12734. // FIXME: It is not clear whether we want to build an lvalue reference
  12735. // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
  12736. // to do the former, while EDG does the latter. Core issue 1249 will
  12737. // clarify, but for now we follow GCC because it's a more permissive and
  12738. // easily defensible position.
  12739. CaptureType = S.Context.getLValueReferenceType(DeclRefType);
  12740. } else {
  12741. // C++11 [expr.prim.lambda]p14:
  12742. // For each entity captured by copy, an unnamed non-static
  12743. // data member is declared in the closure type. The
  12744. // declaration order of these members is unspecified. The type
  12745. // of such a data member is the type of the corresponding
  12746. // captured entity if the entity is not a reference to an
  12747. // object, or the referenced type otherwise. [Note: If the
  12748. // captured entity is a reference to a function, the
  12749. // corresponding data member is also a reference to a
  12750. // function. - end note ]
  12751. if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
  12752. if (!RefType->getPointeeType()->isFunctionType())
  12753. CaptureType = RefType->getPointeeType();
  12754. }
  12755. // Forbid the lambda copy-capture of autoreleasing variables.
  12756. if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
  12757. if (BuildAndDiagnose) {
  12758. S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
  12759. S.Diag(Var->getLocation(), diag::note_previous_decl)
  12760. << Var->getDeclName();
  12761. }
  12762. return false;
  12763. }
  12764. // Make sure that by-copy captures are of a complete and non-abstract type.
  12765. if (BuildAndDiagnose) {
  12766. if (!CaptureType->isDependentType() &&
  12767. S.RequireCompleteType(Loc, CaptureType,
  12768. diag::err_capture_of_incomplete_type,
  12769. Var->getDeclName()))
  12770. return false;
  12771. if (S.RequireNonAbstractType(Loc, CaptureType,
  12772. diag::err_capture_of_abstract_type))
  12773. return false;
  12774. }
  12775. }
  12776. // Capture this variable in the lambda.
  12777. if (BuildAndDiagnose)
  12778. addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
  12779. RefersToCapturedVariable);
  12780. // Compute the type of a reference to this captured variable.
  12781. if (ByRef)
  12782. DeclRefType = CaptureType.getNonReferenceType();
  12783. else {
  12784. // C++ [expr.prim.lambda]p5:
  12785. // The closure type for a lambda-expression has a public inline
  12786. // function call operator [...]. This function call operator is
  12787. // declared const (9.3.1) if and only if the lambda-expression's
  12788. // parameter-declaration-clause is not followed by mutable.
  12789. DeclRefType = CaptureType.getNonReferenceType();
  12790. if (!LSI->Mutable && !CaptureType->isReferenceType())
  12791. DeclRefType.addConst();
  12792. }
  12793. // Add the capture.
  12794. if (BuildAndDiagnose)
  12795. LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
  12796. Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
  12797. return true;
  12798. }
  12799. bool Sema::tryCaptureVariable(
  12800. VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
  12801. SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
  12802. QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
  12803. // An init-capture is notionally from the context surrounding its
  12804. // declaration, but its parent DC is the lambda class.
  12805. DeclContext *VarDC = Var->getDeclContext();
  12806. if (Var->isInitCapture())
  12807. VarDC = VarDC->getParent();
  12808. DeclContext *DC = CurContext;
  12809. const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
  12810. ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
  12811. // We need to sync up the Declaration Context with the
  12812. // FunctionScopeIndexToStopAt
  12813. if (FunctionScopeIndexToStopAt) {
  12814. unsigned FSIndex = FunctionScopes.size() - 1;
  12815. while (FSIndex != MaxFunctionScopesIndex) {
  12816. DC = getLambdaAwareParentOfDeclContext(DC);
  12817. --FSIndex;
  12818. }
  12819. }
  12820. // If the variable is declared in the current context, there is no need to
  12821. // capture it.
  12822. if (VarDC == DC) return true;
  12823. // Capture global variables if it is required to use private copy of this
  12824. // variable.
  12825. bool IsGlobal = !Var->hasLocalStorage();
  12826. if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
  12827. return true;
  12828. Var = Var->getCanonicalDecl();
  12829. // Walk up the stack to determine whether we can capture the variable,
  12830. // performing the "simple" checks that don't depend on type. We stop when
  12831. // we've either hit the declared scope of the variable or find an existing
  12832. // capture of that variable. We start from the innermost capturing-entity
  12833. // (the DC) and ensure that all intervening capturing-entities
  12834. // (blocks/lambdas etc.) between the innermost capturer and the variable`s
  12835. // declcontext can either capture the variable or have already captured
  12836. // the variable.
  12837. CaptureType = Var->getType();
  12838. DeclRefType = CaptureType.getNonReferenceType();
  12839. bool Nested = false;
  12840. bool Explicit = (Kind != TryCapture_Implicit);
  12841. unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
  12842. do {
  12843. // Only block literals, captured statements, and lambda expressions can
  12844. // capture; other scopes don't work.
  12845. DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
  12846. ExprLoc,
  12847. BuildAndDiagnose,
  12848. *this);
  12849. // We need to check for the parent *first* because, if we *have*
  12850. // private-captured a global variable, we need to recursively capture it in
  12851. // intermediate blocks, lambdas, etc.
  12852. if (!ParentDC) {
  12853. if (IsGlobal) {
  12854. FunctionScopesIndex = MaxFunctionScopesIndex - 1;
  12855. break;
  12856. }
  12857. return true;
  12858. }
  12859. FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
  12860. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
  12861. // Check whether we've already captured it.
  12862. if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
  12863. DeclRefType)) {
  12864. CSI->getCapture(Var).markUsed(BuildAndDiagnose);
  12865. break;
  12866. }
  12867. // If we are instantiating a generic lambda call operator body,
  12868. // we do not want to capture new variables. What was captured
  12869. // during either a lambdas transformation or initial parsing
  12870. // should be used.
  12871. if (isGenericLambdaCallOperatorSpecialization(DC)) {
  12872. if (BuildAndDiagnose) {
  12873. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  12874. if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
  12875. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  12876. Diag(Var->getLocation(), diag::note_previous_decl)
  12877. << Var->getDeclName();
  12878. Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
  12879. } else
  12880. diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
  12881. }
  12882. return true;
  12883. }
  12884. // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
  12885. // certain types of variables (unnamed, variably modified types etc.)
  12886. // so check for eligibility.
  12887. if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
  12888. return true;
  12889. // Try to capture variable-length arrays types.
  12890. if (Var->getType()->isVariablyModifiedType()) {
  12891. // We're going to walk down into the type and look for VLA
  12892. // expressions.
  12893. QualType QTy = Var->getType();
  12894. if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
  12895. QTy = PVD->getOriginalType();
  12896. captureVariablyModifiedType(Context, QTy, CSI);
  12897. }
  12898. if (getLangOpts().OpenMP) {
  12899. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  12900. // OpenMP private variables should not be captured in outer scope, so
  12901. // just break here. Similarly, global variables that are captured in a
  12902. // target region should not be captured outside the scope of the region.
  12903. if (RSI->CapRegionKind == CR_OpenMP) {
  12904. bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
  12905. auto IsTargetCap = !IsOpenMPPrivateDecl &&
  12906. isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
  12907. // When we detect target captures we are looking from inside the
  12908. // target region, therefore we need to propagate the capture from the
  12909. // enclosing region. Therefore, the capture is not initially nested.
  12910. if (IsTargetCap)
  12911. adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
  12912. if (IsTargetCap || IsOpenMPPrivateDecl) {
  12913. Nested = !IsTargetCap;
  12914. DeclRefType = DeclRefType.getUnqualifiedType();
  12915. CaptureType = Context.getLValueReferenceType(DeclRefType);
  12916. break;
  12917. }
  12918. }
  12919. }
  12920. }
  12921. if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
  12922. // No capture-default, and this is not an explicit capture
  12923. // so cannot capture this variable.
  12924. if (BuildAndDiagnose) {
  12925. Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
  12926. Diag(Var->getLocation(), diag::note_previous_decl)
  12927. << Var->getDeclName();
  12928. if (cast<LambdaScopeInfo>(CSI)->Lambda)
  12929. Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
  12930. diag::note_lambda_decl);
  12931. // FIXME: If we error out because an outer lambda can not implicitly
  12932. // capture a variable that an inner lambda explicitly captures, we
  12933. // should have the inner lambda do the explicit capture - because
  12934. // it makes for cleaner diagnostics later. This would purely be done
  12935. // so that the diagnostic does not misleadingly claim that a variable
  12936. // can not be captured by a lambda implicitly even though it is captured
  12937. // explicitly. Suggestion:
  12938. // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
  12939. // at the function head
  12940. // - cache the StartingDeclContext - this must be a lambda
  12941. // - captureInLambda in the innermost lambda the variable.
  12942. }
  12943. return true;
  12944. }
  12945. FunctionScopesIndex--;
  12946. DC = ParentDC;
  12947. Explicit = false;
  12948. } while (!VarDC->Equals(DC));
  12949. // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
  12950. // computing the type of the capture at each step, checking type-specific
  12951. // requirements, and adding captures if requested.
  12952. // If the variable had already been captured previously, we start capturing
  12953. // at the lambda nested within that one.
  12954. for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
  12955. ++I) {
  12956. CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
  12957. if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
  12958. if (!captureInBlock(BSI, Var, ExprLoc,
  12959. BuildAndDiagnose, CaptureType,
  12960. DeclRefType, Nested, *this))
  12961. return true;
  12962. Nested = true;
  12963. } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
  12964. if (!captureInCapturedRegion(RSI, Var, ExprLoc,
  12965. BuildAndDiagnose, CaptureType,
  12966. DeclRefType, Nested, *this))
  12967. return true;
  12968. Nested = true;
  12969. } else {
  12970. LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
  12971. if (!captureInLambda(LSI, Var, ExprLoc,
  12972. BuildAndDiagnose, CaptureType,
  12973. DeclRefType, Nested, Kind, EllipsisLoc,
  12974. /*IsTopScope*/I == N - 1, *this))
  12975. return true;
  12976. Nested = true;
  12977. }
  12978. }
  12979. return false;
  12980. }
  12981. bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
  12982. TryCaptureKind Kind, SourceLocation EllipsisLoc) {
  12983. QualType CaptureType;
  12984. QualType DeclRefType;
  12985. return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
  12986. /*BuildAndDiagnose=*/true, CaptureType,
  12987. DeclRefType, nullptr);
  12988. }
  12989. bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
  12990. QualType CaptureType;
  12991. QualType DeclRefType;
  12992. return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  12993. /*BuildAndDiagnose=*/false, CaptureType,
  12994. DeclRefType, nullptr);
  12995. }
  12996. QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
  12997. QualType CaptureType;
  12998. QualType DeclRefType;
  12999. // Determine whether we can capture this variable.
  13000. if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
  13001. /*BuildAndDiagnose=*/false, CaptureType,
  13002. DeclRefType, nullptr))
  13003. return QualType();
  13004. return DeclRefType;
  13005. }
  13006. // If either the type of the variable or the initializer is dependent,
  13007. // return false. Otherwise, determine whether the variable is a constant
  13008. // expression. Use this if you need to know if a variable that might or
  13009. // might not be dependent is truly a constant expression.
  13010. static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
  13011. ASTContext &Context) {
  13012. if (Var->getType()->isDependentType())
  13013. return false;
  13014. const VarDecl *DefVD = nullptr;
  13015. Var->getAnyInitializer(DefVD);
  13016. if (!DefVD)
  13017. return false;
  13018. EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
  13019. Expr *Init = cast<Expr>(Eval->Value);
  13020. if (Init->isValueDependent())
  13021. return false;
  13022. return IsVariableAConstantExpression(Var, Context);
  13023. }
  13024. void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
  13025. // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
  13026. // an object that satisfies the requirements for appearing in a
  13027. // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
  13028. // is immediately applied." This function handles the lvalue-to-rvalue
  13029. // conversion part.
  13030. MaybeODRUseExprs.erase(E->IgnoreParens());
  13031. // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
  13032. // to a variable that is a constant expression, and if so, identify it as
  13033. // a reference to a variable that does not involve an odr-use of that
  13034. // variable.
  13035. if (LambdaScopeInfo *LSI = getCurLambda()) {
  13036. Expr *SansParensExpr = E->IgnoreParens();
  13037. VarDecl *Var = nullptr;
  13038. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
  13039. Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
  13040. else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
  13041. Var = dyn_cast<VarDecl>(ME->getMemberDecl());
  13042. if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
  13043. LSI->markVariableExprAsNonODRUsed(SansParensExpr);
  13044. }
  13045. }
  13046. ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
  13047. Res = CorrectDelayedTyposInExpr(Res);
  13048. if (!Res.isUsable())
  13049. return Res;
  13050. // If a constant-expression is a reference to a variable where we delay
  13051. // deciding whether it is an odr-use, just assume we will apply the
  13052. // lvalue-to-rvalue conversion. In the one case where this doesn't happen
  13053. // (a non-type template argument), we have special handling anyway.
  13054. UpdateMarkingForLValueToRValue(Res.get());
  13055. return Res;
  13056. }
  13057. void Sema::CleanupVarDeclMarking() {
  13058. for (Expr *E : MaybeODRUseExprs) {
  13059. VarDecl *Var;
  13060. SourceLocation Loc;
  13061. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  13062. Var = cast<VarDecl>(DRE->getDecl());
  13063. Loc = DRE->getLocation();
  13064. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  13065. Var = cast<VarDecl>(ME->getMemberDecl());
  13066. Loc = ME->getMemberLoc();
  13067. } else {
  13068. llvm_unreachable("Unexpected expression");
  13069. }
  13070. MarkVarDeclODRUsed(Var, Loc, *this,
  13071. /*MaxFunctionScopeIndex Pointer*/ nullptr);
  13072. }
  13073. MaybeODRUseExprs.clear();
  13074. }
  13075. static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
  13076. VarDecl *Var, Expr *E) {
  13077. assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
  13078. "Invalid Expr argument to DoMarkVarDeclReferenced");
  13079. Var->setReferenced();
  13080. TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
  13081. bool OdrUseContext = isOdrUseContext(SemaRef);
  13082. bool UsableInConstantExpr =
  13083. Var->isUsableInConstantExpressions(SemaRef.Context);
  13084. bool NeedDefinition =
  13085. OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
  13086. VarTemplateSpecializationDecl *VarSpec =
  13087. dyn_cast<VarTemplateSpecializationDecl>(Var);
  13088. assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
  13089. "Can't instantiate a partial template specialization.");
  13090. // If this might be a member specialization of a static data member, check
  13091. // the specialization is visible. We already did the checks for variable
  13092. // template specializations when we created them.
  13093. if (NeedDefinition && TSK != TSK_Undeclared &&
  13094. !isa<VarTemplateSpecializationDecl>(Var))
  13095. SemaRef.checkSpecializationVisibility(Loc, Var);
  13096. // Perform implicit instantiation of static data members, static data member
  13097. // templates of class templates, and variable template specializations. Delay
  13098. // instantiations of variable templates, except for those that could be used
  13099. // in a constant expression.
  13100. if (NeedDefinition && isTemplateInstantiation(TSK)) {
  13101. // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
  13102. // instantiation declaration if a variable is usable in a constant
  13103. // expression (among other cases).
  13104. bool TryInstantiating =
  13105. TSK == TSK_ImplicitInstantiation ||
  13106. (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
  13107. if (TryInstantiating) {
  13108. SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
  13109. bool FirstInstantiation = PointOfInstantiation.isInvalid();
  13110. if (FirstInstantiation) {
  13111. PointOfInstantiation = Loc;
  13112. Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
  13113. }
  13114. bool InstantiationDependent = false;
  13115. bool IsNonDependent =
  13116. VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
  13117. VarSpec->getTemplateArgsInfo(), InstantiationDependent)
  13118. : true;
  13119. // Do not instantiate specializations that are still type-dependent.
  13120. if (IsNonDependent) {
  13121. if (UsableInConstantExpr) {
  13122. // Do not defer instantiations of variables that could be used in a
  13123. // constant expression.
  13124. SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
  13125. } else if (FirstInstantiation ||
  13126. isa<VarTemplateSpecializationDecl>(Var)) {
  13127. // FIXME: For a specialization of a variable template, we don't
  13128. // distinguish between "declaration and type implicitly instantiated"
  13129. // and "implicit instantiation of definition requested", so we have
  13130. // no direct way to avoid enqueueing the pending instantiation
  13131. // multiple times.
  13132. SemaRef.PendingInstantiations
  13133. .push_back(std::make_pair(Var, PointOfInstantiation));
  13134. }
  13135. }
  13136. }
  13137. }
  13138. // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
  13139. // the requirements for appearing in a constant expression (5.19) and, if
  13140. // it is an object, the lvalue-to-rvalue conversion (4.1)
  13141. // is immediately applied." We check the first part here, and
  13142. // Sema::UpdateMarkingForLValueToRValue deals with the second part.
  13143. // Note that we use the C++11 definition everywhere because nothing in
  13144. // C++03 depends on whether we get the C++03 version correct. The second
  13145. // part does not apply to references, since they are not objects.
  13146. if (OdrUseContext && E &&
  13147. IsVariableAConstantExpression(Var, SemaRef.Context)) {
  13148. // A reference initialized by a constant expression can never be
  13149. // odr-used, so simply ignore it.
  13150. if (!Var->getType()->isReferenceType() ||
  13151. (SemaRef.LangOpts.OpenMP && SemaRef.IsOpenMPCapturedDecl(Var)))
  13152. SemaRef.MaybeODRUseExprs.insert(E);
  13153. } else if (OdrUseContext) {
  13154. MarkVarDeclODRUsed(Var, Loc, SemaRef,
  13155. /*MaxFunctionScopeIndex ptr*/ nullptr);
  13156. } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
  13157. // If this is a dependent context, we don't need to mark variables as
  13158. // odr-used, but we may still need to track them for lambda capture.
  13159. // FIXME: Do we also need to do this inside dependent typeid expressions
  13160. // (which are modeled as unevaluated at this point)?
  13161. const bool RefersToEnclosingScope =
  13162. (SemaRef.CurContext != Var->getDeclContext() &&
  13163. Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
  13164. if (RefersToEnclosingScope) {
  13165. LambdaScopeInfo *const LSI =
  13166. SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
  13167. if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
  13168. // If a variable could potentially be odr-used, defer marking it so
  13169. // until we finish analyzing the full expression for any
  13170. // lvalue-to-rvalue
  13171. // or discarded value conversions that would obviate odr-use.
  13172. // Add it to the list of potential captures that will be analyzed
  13173. // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
  13174. // unless the variable is a reference that was initialized by a constant
  13175. // expression (this will never need to be captured or odr-used).
  13176. assert(E && "Capture variable should be used in an expression.");
  13177. if (!Var->getType()->isReferenceType() ||
  13178. !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
  13179. LSI->addPotentialCapture(E->IgnoreParens());
  13180. }
  13181. }
  13182. }
  13183. }
  13184. /// \brief Mark a variable referenced, and check whether it is odr-used
  13185. /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
  13186. /// used directly for normal expressions referring to VarDecl.
  13187. void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
  13188. DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
  13189. }
  13190. static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
  13191. Decl *D, Expr *E, bool MightBeOdrUse) {
  13192. if (SemaRef.isInOpenMPDeclareTargetContext())
  13193. SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
  13194. if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
  13195. DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
  13196. return;
  13197. }
  13198. SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
  13199. // If this is a call to a method via a cast, also mark the method in the
  13200. // derived class used in case codegen can devirtualize the call.
  13201. const MemberExpr *ME = dyn_cast<MemberExpr>(E);
  13202. if (!ME)
  13203. return;
  13204. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
  13205. if (!MD)
  13206. return;
  13207. // Only attempt to devirtualize if this is truly a virtual call.
  13208. bool IsVirtualCall = MD->isVirtual() &&
  13209. ME->performsVirtualDispatch(SemaRef.getLangOpts());
  13210. if (!IsVirtualCall)
  13211. return;
  13212. // If it's possible to devirtualize the call, mark the called function
  13213. // referenced.
  13214. CXXMethodDecl *DM = MD->getDevirtualizedMethod(
  13215. ME->getBase(), SemaRef.getLangOpts().AppleKext);
  13216. if (DM)
  13217. SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
  13218. }
  13219. /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
  13220. void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
  13221. // TODO: update this with DR# once a defect report is filed.
  13222. // C++11 defect. The address of a pure member should not be an ODR use, even
  13223. // if it's a qualified reference.
  13224. bool OdrUse = true;
  13225. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
  13226. if (Method->isVirtual() &&
  13227. !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
  13228. OdrUse = false;
  13229. MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
  13230. }
  13231. /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
  13232. void Sema::MarkMemberReferenced(MemberExpr *E) {
  13233. // C++11 [basic.def.odr]p2:
  13234. // A non-overloaded function whose name appears as a potentially-evaluated
  13235. // expression or a member of a set of candidate functions, if selected by
  13236. // overload resolution when referred to from a potentially-evaluated
  13237. // expression, is odr-used, unless it is a pure virtual function and its
  13238. // name is not explicitly qualified.
  13239. bool MightBeOdrUse = true;
  13240. if (E->performsVirtualDispatch(getLangOpts())) {
  13241. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
  13242. if (Method->isPure())
  13243. MightBeOdrUse = false;
  13244. }
  13245. SourceLocation Loc = E->getMemberLoc().isValid() ?
  13246. E->getMemberLoc() : E->getLocStart();
  13247. MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
  13248. }
  13249. /// \brief Perform marking for a reference to an arbitrary declaration. It
  13250. /// marks the declaration referenced, and performs odr-use checking for
  13251. /// functions and variables. This method should not be used when building a
  13252. /// normal expression which refers to a variable.
  13253. void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
  13254. bool MightBeOdrUse) {
  13255. if (MightBeOdrUse) {
  13256. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13257. MarkVariableReferenced(Loc, VD);
  13258. return;
  13259. }
  13260. }
  13261. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  13262. MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
  13263. return;
  13264. }
  13265. D->setReferenced();
  13266. }
  13267. namespace {
  13268. // Mark all of the declarations used by a type as referenced.
  13269. // FIXME: Not fully implemented yet! We need to have a better understanding
  13270. // of when we're entering a context we should not recurse into.
  13271. // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
  13272. // TreeTransforms rebuilding the type in a new context. Rather than
  13273. // duplicating the TreeTransform logic, we should consider reusing it here.
  13274. // Currently that causes problems when rebuilding LambdaExprs.
  13275. class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
  13276. Sema &S;
  13277. SourceLocation Loc;
  13278. public:
  13279. typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
  13280. MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
  13281. bool TraverseTemplateArgument(const TemplateArgument &Arg);
  13282. };
  13283. }
  13284. bool MarkReferencedDecls::TraverseTemplateArgument(
  13285. const TemplateArgument &Arg) {
  13286. {
  13287. // A non-type template argument is a constant-evaluated context.
  13288. EnterExpressionEvaluationContext Evaluated(
  13289. S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  13290. if (Arg.getKind() == TemplateArgument::Declaration) {
  13291. if (Decl *D = Arg.getAsDecl())
  13292. S.MarkAnyDeclReferenced(Loc, D, true);
  13293. } else if (Arg.getKind() == TemplateArgument::Expression) {
  13294. S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
  13295. }
  13296. }
  13297. return Inherited::TraverseTemplateArgument(Arg);
  13298. }
  13299. void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
  13300. MarkReferencedDecls Marker(*this, Loc);
  13301. Marker.TraverseType(T);
  13302. }
  13303. namespace {
  13304. /// \brief Helper class that marks all of the declarations referenced by
  13305. /// potentially-evaluated subexpressions as "referenced".
  13306. class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
  13307. Sema &S;
  13308. bool SkipLocalVariables;
  13309. public:
  13310. typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
  13311. EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
  13312. : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
  13313. void VisitDeclRefExpr(DeclRefExpr *E) {
  13314. // If we were asked not to visit local variables, don't.
  13315. if (SkipLocalVariables) {
  13316. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
  13317. if (VD->hasLocalStorage())
  13318. return;
  13319. }
  13320. S.MarkDeclRefReferenced(E);
  13321. }
  13322. void VisitMemberExpr(MemberExpr *E) {
  13323. S.MarkMemberReferenced(E);
  13324. Inherited::VisitMemberExpr(E);
  13325. }
  13326. void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  13327. S.MarkFunctionReferenced(E->getLocStart(),
  13328. const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
  13329. Visit(E->getSubExpr());
  13330. }
  13331. void VisitCXXNewExpr(CXXNewExpr *E) {
  13332. if (E->getOperatorNew())
  13333. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
  13334. if (E->getOperatorDelete())
  13335. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  13336. Inherited::VisitCXXNewExpr(E);
  13337. }
  13338. void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  13339. if (E->getOperatorDelete())
  13340. S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
  13341. QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
  13342. if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
  13343. CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
  13344. S.MarkFunctionReferenced(E->getLocStart(),
  13345. S.LookupDestructor(Record));
  13346. }
  13347. Inherited::VisitCXXDeleteExpr(E);
  13348. }
  13349. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  13350. S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
  13351. Inherited::VisitCXXConstructExpr(E);
  13352. }
  13353. void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
  13354. Visit(E->getExpr());
  13355. }
  13356. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  13357. Inherited::VisitImplicitCastExpr(E);
  13358. if (E->getCastKind() == CK_LValueToRValue)
  13359. S.UpdateMarkingForLValueToRValue(E->getSubExpr());
  13360. }
  13361. };
  13362. }
  13363. /// \brief Mark any declarations that appear within this expression or any
  13364. /// potentially-evaluated subexpressions as "referenced".
  13365. ///
  13366. /// \param SkipLocalVariables If true, don't mark local variables as
  13367. /// 'referenced'.
  13368. void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
  13369. bool SkipLocalVariables) {
  13370. EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
  13371. }
  13372. /// \brief Emit a diagnostic that describes an effect on the run-time behavior
  13373. /// of the program being compiled.
  13374. ///
  13375. /// This routine emits the given diagnostic when the code currently being
  13376. /// type-checked is "potentially evaluated", meaning that there is a
  13377. /// possibility that the code will actually be executable. Code in sizeof()
  13378. /// expressions, code used only during overload resolution, etc., are not
  13379. /// potentially evaluated. This routine will suppress such diagnostics or,
  13380. /// in the absolutely nutty case of potentially potentially evaluated
  13381. /// expressions (C++ typeid), queue the diagnostic to potentially emit it
  13382. /// later.
  13383. ///
  13384. /// This routine should be used for all diagnostics that describe the run-time
  13385. /// behavior of a program, such as passing a non-POD value through an ellipsis.
  13386. /// Failure to do so will likely result in spurious diagnostics or failures
  13387. /// during overload resolution or within sizeof/alignof/typeof/typeid.
  13388. bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
  13389. const PartialDiagnostic &PD) {
  13390. switch (ExprEvalContexts.back().Context) {
  13391. case ExpressionEvaluationContext::Unevaluated:
  13392. case ExpressionEvaluationContext::UnevaluatedList:
  13393. case ExpressionEvaluationContext::UnevaluatedAbstract:
  13394. case ExpressionEvaluationContext::DiscardedStatement:
  13395. // The argument will never be evaluated, so don't complain.
  13396. break;
  13397. case ExpressionEvaluationContext::ConstantEvaluated:
  13398. // Relevant diagnostics should be produced by constant evaluation.
  13399. break;
  13400. case ExpressionEvaluationContext::PotentiallyEvaluated:
  13401. case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
  13402. if (Statement && getCurFunctionOrMethodDecl()) {
  13403. FunctionScopes.back()->PossiblyUnreachableDiags.
  13404. push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
  13405. return true;
  13406. }
  13407. // The initializer of a constexpr variable or of the first declaration of a
  13408. // static data member is not syntactically a constant evaluated constant,
  13409. // but nonetheless is always required to be a constant expression, so we
  13410. // can skip diagnosing.
  13411. // FIXME: Using the mangling context here is a hack.
  13412. if (auto *VD = dyn_cast_or_null<VarDecl>(
  13413. ExprEvalContexts.back().ManglingContextDecl)) {
  13414. if (VD->isConstexpr() ||
  13415. (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
  13416. break;
  13417. // FIXME: For any other kind of variable, we should build a CFG for its
  13418. // initializer and check whether the context in question is reachable.
  13419. }
  13420. Diag(Loc, PD);
  13421. return true;
  13422. }
  13423. return false;
  13424. }
  13425. bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
  13426. CallExpr *CE, FunctionDecl *FD) {
  13427. if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
  13428. return false;
  13429. // If we're inside a decltype's expression, don't check for a valid return
  13430. // type or construct temporaries until we know whether this is the last call.
  13431. if (ExprEvalContexts.back().IsDecltype) {
  13432. ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
  13433. return false;
  13434. }
  13435. class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
  13436. FunctionDecl *FD;
  13437. CallExpr *CE;
  13438. public:
  13439. CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
  13440. : FD(FD), CE(CE) { }
  13441. void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
  13442. if (!FD) {
  13443. S.Diag(Loc, diag::err_call_incomplete_return)
  13444. << T << CE->getSourceRange();
  13445. return;
  13446. }
  13447. S.Diag(Loc, diag::err_call_function_incomplete_return)
  13448. << CE->getSourceRange() << FD->getDeclName() << T;
  13449. S.Diag(FD->getLocation(), diag::note_entity_declared_at)
  13450. << FD->getDeclName();
  13451. }
  13452. } Diagnoser(FD, CE);
  13453. if (RequireCompleteType(Loc, ReturnType, Diagnoser))
  13454. return true;
  13455. return false;
  13456. }
  13457. // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
  13458. // will prevent this condition from triggering, which is what we want.
  13459. void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
  13460. SourceLocation Loc;
  13461. unsigned diagnostic = diag::warn_condition_is_assignment;
  13462. bool IsOrAssign = false;
  13463. if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
  13464. if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
  13465. return;
  13466. IsOrAssign = Op->getOpcode() == BO_OrAssign;
  13467. // Greylist some idioms by putting them into a warning subcategory.
  13468. if (ObjCMessageExpr *ME
  13469. = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
  13470. Selector Sel = ME->getSelector();
  13471. // self = [<foo> init...]
  13472. if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
  13473. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  13474. // <foo> = [<bar> nextObject]
  13475. else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
  13476. diagnostic = diag::warn_condition_is_idiomatic_assignment;
  13477. }
  13478. Loc = Op->getOperatorLoc();
  13479. } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
  13480. if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
  13481. return;
  13482. IsOrAssign = Op->getOperator() == OO_PipeEqual;
  13483. Loc = Op->getOperatorLoc();
  13484. } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  13485. return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
  13486. else {
  13487. // Not an assignment.
  13488. return;
  13489. }
  13490. Diag(Loc, diagnostic) << E->getSourceRange();
  13491. SourceLocation Open = E->getLocStart();
  13492. SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
  13493. Diag(Loc, diag::note_condition_assign_silence)
  13494. << FixItHint::CreateInsertion(Open, "(")
  13495. << FixItHint::CreateInsertion(Close, ")");
  13496. if (IsOrAssign)
  13497. Diag(Loc, diag::note_condition_or_assign_to_comparison)
  13498. << FixItHint::CreateReplacement(Loc, "!=");
  13499. else
  13500. Diag(Loc, diag::note_condition_assign_to_comparison)
  13501. << FixItHint::CreateReplacement(Loc, "==");
  13502. }
  13503. /// \brief Redundant parentheses over an equality comparison can indicate
  13504. /// that the user intended an assignment used as condition.
  13505. void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
  13506. // Don't warn if the parens came from a macro.
  13507. SourceLocation parenLoc = ParenE->getLocStart();
  13508. if (parenLoc.isInvalid() || parenLoc.isMacroID())
  13509. return;
  13510. // Don't warn for dependent expressions.
  13511. if (ParenE->isTypeDependent())
  13512. return;
  13513. Expr *E = ParenE->IgnoreParens();
  13514. if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
  13515. if (opE->getOpcode() == BO_EQ &&
  13516. opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
  13517. == Expr::MLV_Valid) {
  13518. SourceLocation Loc = opE->getOperatorLoc();
  13519. Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
  13520. SourceRange ParenERange = ParenE->getSourceRange();
  13521. Diag(Loc, diag::note_equality_comparison_silence)
  13522. << FixItHint::CreateRemoval(ParenERange.getBegin())
  13523. << FixItHint::CreateRemoval(ParenERange.getEnd());
  13524. Diag(Loc, diag::note_equality_comparison_to_assign)
  13525. << FixItHint::CreateReplacement(Loc, "=");
  13526. }
  13527. }
  13528. ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
  13529. bool IsConstexpr) {
  13530. DiagnoseAssignmentAsCondition(E);
  13531. if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
  13532. DiagnoseEqualityWithExtraParens(parenE);
  13533. ExprResult result = CheckPlaceholderExpr(E);
  13534. if (result.isInvalid()) return ExprError();
  13535. E = result.get();
  13536. if (!E->isTypeDependent()) {
  13537. if (getLangOpts().CPlusPlus)
  13538. return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
  13539. ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
  13540. if (ERes.isInvalid())
  13541. return ExprError();
  13542. E = ERes.get();
  13543. QualType T = E->getType();
  13544. if (!T->isScalarType()) { // C99 6.8.4.1p1
  13545. Diag(Loc, diag::err_typecheck_statement_requires_scalar)
  13546. << T << E->getSourceRange();
  13547. return ExprError();
  13548. }
  13549. CheckBoolLikeConversion(E, Loc);
  13550. }
  13551. return E;
  13552. }
  13553. Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
  13554. Expr *SubExpr, ConditionKind CK) {
  13555. // Empty conditions are valid in for-statements.
  13556. if (!SubExpr)
  13557. return ConditionResult();
  13558. ExprResult Cond;
  13559. switch (CK) {
  13560. case ConditionKind::Boolean:
  13561. Cond = CheckBooleanCondition(Loc, SubExpr);
  13562. break;
  13563. case ConditionKind::ConstexprIf:
  13564. Cond = CheckBooleanCondition(Loc, SubExpr, true);
  13565. break;
  13566. case ConditionKind::Switch:
  13567. Cond = CheckSwitchCondition(Loc, SubExpr);
  13568. break;
  13569. }
  13570. if (Cond.isInvalid())
  13571. return ConditionError();
  13572. // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
  13573. FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
  13574. if (!FullExpr.get())
  13575. return ConditionError();
  13576. return ConditionResult(*this, nullptr, FullExpr,
  13577. CK == ConditionKind::ConstexprIf);
  13578. }
  13579. namespace {
  13580. /// A visitor for rebuilding a call to an __unknown_any expression
  13581. /// to have an appropriate type.
  13582. struct RebuildUnknownAnyFunction
  13583. : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
  13584. Sema &S;
  13585. RebuildUnknownAnyFunction(Sema &S) : S(S) {}
  13586. ExprResult VisitStmt(Stmt *S) {
  13587. llvm_unreachable("unexpected statement!");
  13588. }
  13589. ExprResult VisitExpr(Expr *E) {
  13590. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
  13591. << E->getSourceRange();
  13592. return ExprError();
  13593. }
  13594. /// Rebuild an expression which simply semantically wraps another
  13595. /// expression which it shares the type and value kind of.
  13596. template <class T> ExprResult rebuildSugarExpr(T *E) {
  13597. ExprResult SubResult = Visit(E->getSubExpr());
  13598. if (SubResult.isInvalid()) return ExprError();
  13599. Expr *SubExpr = SubResult.get();
  13600. E->setSubExpr(SubExpr);
  13601. E->setType(SubExpr->getType());
  13602. E->setValueKind(SubExpr->getValueKind());
  13603. assert(E->getObjectKind() == OK_Ordinary);
  13604. return E;
  13605. }
  13606. ExprResult VisitParenExpr(ParenExpr *E) {
  13607. return rebuildSugarExpr(E);
  13608. }
  13609. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  13610. return rebuildSugarExpr(E);
  13611. }
  13612. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  13613. ExprResult SubResult = Visit(E->getSubExpr());
  13614. if (SubResult.isInvalid()) return ExprError();
  13615. Expr *SubExpr = SubResult.get();
  13616. E->setSubExpr(SubExpr);
  13617. E->setType(S.Context.getPointerType(SubExpr->getType()));
  13618. assert(E->getValueKind() == VK_RValue);
  13619. assert(E->getObjectKind() == OK_Ordinary);
  13620. return E;
  13621. }
  13622. ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
  13623. if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
  13624. E->setType(VD->getType());
  13625. assert(E->getValueKind() == VK_RValue);
  13626. if (S.getLangOpts().CPlusPlus &&
  13627. !(isa<CXXMethodDecl>(VD) &&
  13628. cast<CXXMethodDecl>(VD)->isInstance()))
  13629. E->setValueKind(VK_LValue);
  13630. return E;
  13631. }
  13632. ExprResult VisitMemberExpr(MemberExpr *E) {
  13633. return resolveDecl(E, E->getMemberDecl());
  13634. }
  13635. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  13636. return resolveDecl(E, E->getDecl());
  13637. }
  13638. };
  13639. }
  13640. /// Given a function expression of unknown-any type, try to rebuild it
  13641. /// to have a function type.
  13642. static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
  13643. ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
  13644. if (Result.isInvalid()) return ExprError();
  13645. return S.DefaultFunctionArrayConversion(Result.get());
  13646. }
  13647. namespace {
  13648. /// A visitor for rebuilding an expression of type __unknown_anytype
  13649. /// into one which resolves the type directly on the referring
  13650. /// expression. Strict preservation of the original source
  13651. /// structure is not a goal.
  13652. struct RebuildUnknownAnyExpr
  13653. : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
  13654. Sema &S;
  13655. /// The current destination type.
  13656. QualType DestType;
  13657. RebuildUnknownAnyExpr(Sema &S, QualType CastType)
  13658. : S(S), DestType(CastType) {}
  13659. ExprResult VisitStmt(Stmt *S) {
  13660. llvm_unreachable("unexpected statement!");
  13661. }
  13662. ExprResult VisitExpr(Expr *E) {
  13663. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  13664. << E->getSourceRange();
  13665. return ExprError();
  13666. }
  13667. ExprResult VisitCallExpr(CallExpr *E);
  13668. ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
  13669. /// Rebuild an expression which simply semantically wraps another
  13670. /// expression which it shares the type and value kind of.
  13671. template <class T> ExprResult rebuildSugarExpr(T *E) {
  13672. ExprResult SubResult = Visit(E->getSubExpr());
  13673. if (SubResult.isInvalid()) return ExprError();
  13674. Expr *SubExpr = SubResult.get();
  13675. E->setSubExpr(SubExpr);
  13676. E->setType(SubExpr->getType());
  13677. E->setValueKind(SubExpr->getValueKind());
  13678. assert(E->getObjectKind() == OK_Ordinary);
  13679. return E;
  13680. }
  13681. ExprResult VisitParenExpr(ParenExpr *E) {
  13682. return rebuildSugarExpr(E);
  13683. }
  13684. ExprResult VisitUnaryExtension(UnaryOperator *E) {
  13685. return rebuildSugarExpr(E);
  13686. }
  13687. ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
  13688. const PointerType *Ptr = DestType->getAs<PointerType>();
  13689. if (!Ptr) {
  13690. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
  13691. << E->getSourceRange();
  13692. return ExprError();
  13693. }
  13694. if (isa<CallExpr>(E->getSubExpr())) {
  13695. S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
  13696. << E->getSourceRange();
  13697. return ExprError();
  13698. }
  13699. assert(E->getValueKind() == VK_RValue);
  13700. assert(E->getObjectKind() == OK_Ordinary);
  13701. E->setType(DestType);
  13702. // Build the sub-expression as if it were an object of the pointee type.
  13703. DestType = Ptr->getPointeeType();
  13704. ExprResult SubResult = Visit(E->getSubExpr());
  13705. if (SubResult.isInvalid()) return ExprError();
  13706. E->setSubExpr(SubResult.get());
  13707. return E;
  13708. }
  13709. ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
  13710. ExprResult resolveDecl(Expr *E, ValueDecl *VD);
  13711. ExprResult VisitMemberExpr(MemberExpr *E) {
  13712. return resolveDecl(E, E->getMemberDecl());
  13713. }
  13714. ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
  13715. return resolveDecl(E, E->getDecl());
  13716. }
  13717. };
  13718. }
  13719. /// Rebuilds a call expression which yielded __unknown_anytype.
  13720. ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
  13721. Expr *CalleeExpr = E->getCallee();
  13722. enum FnKind {
  13723. FK_MemberFunction,
  13724. FK_FunctionPointer,
  13725. FK_BlockPointer
  13726. };
  13727. FnKind Kind;
  13728. QualType CalleeType = CalleeExpr->getType();
  13729. if (CalleeType == S.Context.BoundMemberTy) {
  13730. assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
  13731. Kind = FK_MemberFunction;
  13732. CalleeType = Expr::findBoundMemberType(CalleeExpr);
  13733. } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
  13734. CalleeType = Ptr->getPointeeType();
  13735. Kind = FK_FunctionPointer;
  13736. } else {
  13737. CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
  13738. Kind = FK_BlockPointer;
  13739. }
  13740. const FunctionType *FnType = CalleeType->castAs<FunctionType>();
  13741. // Verify that this is a legal result type of a function.
  13742. if (DestType->isArrayType() || DestType->isFunctionType()) {
  13743. unsigned diagID = diag::err_func_returning_array_function;
  13744. if (Kind == FK_BlockPointer)
  13745. diagID = diag::err_block_returning_array_function;
  13746. S.Diag(E->getExprLoc(), diagID)
  13747. << DestType->isFunctionType() << DestType;
  13748. return ExprError();
  13749. }
  13750. // Otherwise, go ahead and set DestType as the call's result.
  13751. E->setType(DestType.getNonLValueExprType(S.Context));
  13752. E->setValueKind(Expr::getValueKindForType(DestType));
  13753. assert(E->getObjectKind() == OK_Ordinary);
  13754. // Rebuild the function type, replacing the result type with DestType.
  13755. const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
  13756. if (Proto) {
  13757. // __unknown_anytype(...) is a special case used by the debugger when
  13758. // it has no idea what a function's signature is.
  13759. //
  13760. // We want to build this call essentially under the K&R
  13761. // unprototyped rules, but making a FunctionNoProtoType in C++
  13762. // would foul up all sorts of assumptions. However, we cannot
  13763. // simply pass all arguments as variadic arguments, nor can we
  13764. // portably just call the function under a non-variadic type; see
  13765. // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
  13766. // However, it turns out that in practice it is generally safe to
  13767. // call a function declared as "A foo(B,C,D);" under the prototype
  13768. // "A foo(B,C,D,...);". The only known exception is with the
  13769. // Windows ABI, where any variadic function is implicitly cdecl
  13770. // regardless of its normal CC. Therefore we change the parameter
  13771. // types to match the types of the arguments.
  13772. //
  13773. // This is a hack, but it is far superior to moving the
  13774. // corresponding target-specific code from IR-gen to Sema/AST.
  13775. ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
  13776. SmallVector<QualType, 8> ArgTypes;
  13777. if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
  13778. ArgTypes.reserve(E->getNumArgs());
  13779. for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
  13780. Expr *Arg = E->getArg(i);
  13781. QualType ArgType = Arg->getType();
  13782. if (E->isLValue()) {
  13783. ArgType = S.Context.getLValueReferenceType(ArgType);
  13784. } else if (E->isXValue()) {
  13785. ArgType = S.Context.getRValueReferenceType(ArgType);
  13786. }
  13787. ArgTypes.push_back(ArgType);
  13788. }
  13789. ParamTypes = ArgTypes;
  13790. }
  13791. DestType = S.Context.getFunctionType(DestType, ParamTypes,
  13792. Proto->getExtProtoInfo());
  13793. } else {
  13794. DestType = S.Context.getFunctionNoProtoType(DestType,
  13795. FnType->getExtInfo());
  13796. }
  13797. // Rebuild the appropriate pointer-to-function type.
  13798. switch (Kind) {
  13799. case FK_MemberFunction:
  13800. // Nothing to do.
  13801. break;
  13802. case FK_FunctionPointer:
  13803. DestType = S.Context.getPointerType(DestType);
  13804. break;
  13805. case FK_BlockPointer:
  13806. DestType = S.Context.getBlockPointerType(DestType);
  13807. break;
  13808. }
  13809. // Finally, we can recurse.
  13810. ExprResult CalleeResult = Visit(CalleeExpr);
  13811. if (!CalleeResult.isUsable()) return ExprError();
  13812. E->setCallee(CalleeResult.get());
  13813. // Bind a temporary if necessary.
  13814. return S.MaybeBindToTemporary(E);
  13815. }
  13816. ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
  13817. // Verify that this is a legal result type of a call.
  13818. if (DestType->isArrayType() || DestType->isFunctionType()) {
  13819. S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
  13820. << DestType->isFunctionType() << DestType;
  13821. return ExprError();
  13822. }
  13823. // Rewrite the method result type if available.
  13824. if (ObjCMethodDecl *Method = E->getMethodDecl()) {
  13825. assert(Method->getReturnType() == S.Context.UnknownAnyTy);
  13826. Method->setReturnType(DestType);
  13827. }
  13828. // Change the type of the message.
  13829. E->setType(DestType.getNonReferenceType());
  13830. E->setValueKind(Expr::getValueKindForType(DestType));
  13831. return S.MaybeBindToTemporary(E);
  13832. }
  13833. ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
  13834. // The only case we should ever see here is a function-to-pointer decay.
  13835. if (E->getCastKind() == CK_FunctionToPointerDecay) {
  13836. assert(E->getValueKind() == VK_RValue);
  13837. assert(E->getObjectKind() == OK_Ordinary);
  13838. E->setType(DestType);
  13839. // Rebuild the sub-expression as the pointee (function) type.
  13840. DestType = DestType->castAs<PointerType>()->getPointeeType();
  13841. ExprResult Result = Visit(E->getSubExpr());
  13842. if (!Result.isUsable()) return ExprError();
  13843. E->setSubExpr(Result.get());
  13844. return E;
  13845. } else if (E->getCastKind() == CK_LValueToRValue) {
  13846. assert(E->getValueKind() == VK_RValue);
  13847. assert(E->getObjectKind() == OK_Ordinary);
  13848. assert(isa<BlockPointerType>(E->getType()));
  13849. E->setType(DestType);
  13850. // The sub-expression has to be a lvalue reference, so rebuild it as such.
  13851. DestType = S.Context.getLValueReferenceType(DestType);
  13852. ExprResult Result = Visit(E->getSubExpr());
  13853. if (!Result.isUsable()) return ExprError();
  13854. E->setSubExpr(Result.get());
  13855. return E;
  13856. } else {
  13857. llvm_unreachable("Unhandled cast type!");
  13858. }
  13859. }
  13860. ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
  13861. ExprValueKind ValueKind = VK_LValue;
  13862. QualType Type = DestType;
  13863. // We know how to make this work for certain kinds of decls:
  13864. // - functions
  13865. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
  13866. if (const PointerType *Ptr = Type->getAs<PointerType>()) {
  13867. DestType = Ptr->getPointeeType();
  13868. ExprResult Result = resolveDecl(E, VD);
  13869. if (Result.isInvalid()) return ExprError();
  13870. return S.ImpCastExprToType(Result.get(), Type,
  13871. CK_FunctionToPointerDecay, VK_RValue);
  13872. }
  13873. if (!Type->isFunctionType()) {
  13874. S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
  13875. << VD << E->getSourceRange();
  13876. return ExprError();
  13877. }
  13878. if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
  13879. // We must match the FunctionDecl's type to the hack introduced in
  13880. // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
  13881. // type. See the lengthy commentary in that routine.
  13882. QualType FDT = FD->getType();
  13883. const FunctionType *FnType = FDT->castAs<FunctionType>();
  13884. const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
  13885. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
  13886. if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
  13887. SourceLocation Loc = FD->getLocation();
  13888. FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
  13889. FD->getDeclContext(),
  13890. Loc, Loc, FD->getNameInfo().getName(),
  13891. DestType, FD->getTypeSourceInfo(),
  13892. SC_None, false/*isInlineSpecified*/,
  13893. FD->hasPrototype(),
  13894. false/*isConstexprSpecified*/);
  13895. if (FD->getQualifier())
  13896. NewFD->setQualifierInfo(FD->getQualifierLoc());
  13897. SmallVector<ParmVarDecl*, 16> Params;
  13898. for (const auto &AI : FT->param_types()) {
  13899. ParmVarDecl *Param =
  13900. S.BuildParmVarDeclForTypedef(FD, Loc, AI);
  13901. Param->setScopeInfo(0, Params.size());
  13902. Params.push_back(Param);
  13903. }
  13904. NewFD->setParams(Params);
  13905. DRE->setDecl(NewFD);
  13906. VD = DRE->getDecl();
  13907. }
  13908. }
  13909. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  13910. if (MD->isInstance()) {
  13911. ValueKind = VK_RValue;
  13912. Type = S.Context.BoundMemberTy;
  13913. }
  13914. // Function references aren't l-values in C.
  13915. if (!S.getLangOpts().CPlusPlus)
  13916. ValueKind = VK_RValue;
  13917. // - variables
  13918. } else if (isa<VarDecl>(VD)) {
  13919. if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
  13920. Type = RefTy->getPointeeType();
  13921. } else if (Type->isFunctionType()) {
  13922. S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
  13923. << VD << E->getSourceRange();
  13924. return ExprError();
  13925. }
  13926. // - nothing else
  13927. } else {
  13928. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
  13929. << VD << E->getSourceRange();
  13930. return ExprError();
  13931. }
  13932. // Modifying the declaration like this is friendly to IR-gen but
  13933. // also really dangerous.
  13934. VD->setType(DestType);
  13935. E->setType(Type);
  13936. E->setValueKind(ValueKind);
  13937. return E;
  13938. }
  13939. /// Check a cast of an unknown-any type. We intentionally only
  13940. /// trigger this for C-style casts.
  13941. ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
  13942. Expr *CastExpr, CastKind &CastKind,
  13943. ExprValueKind &VK, CXXCastPath &Path) {
  13944. // The type we're casting to must be either void or complete.
  13945. if (!CastType->isVoidType() &&
  13946. RequireCompleteType(TypeRange.getBegin(), CastType,
  13947. diag::err_typecheck_cast_to_incomplete))
  13948. return ExprError();
  13949. // Rewrite the casted expression from scratch.
  13950. ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
  13951. if (!result.isUsable()) return ExprError();
  13952. CastExpr = result.get();
  13953. VK = CastExpr->getValueKind();
  13954. CastKind = CK_NoOp;
  13955. return CastExpr;
  13956. }
  13957. ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
  13958. return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
  13959. }
  13960. ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
  13961. Expr *arg, QualType &paramType) {
  13962. // If the syntactic form of the argument is not an explicit cast of
  13963. // any sort, just do default argument promotion.
  13964. ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
  13965. if (!castArg) {
  13966. ExprResult result = DefaultArgumentPromotion(arg);
  13967. if (result.isInvalid()) return ExprError();
  13968. paramType = result.get()->getType();
  13969. return result;
  13970. }
  13971. // Otherwise, use the type that was written in the explicit cast.
  13972. assert(!arg->hasPlaceholderType());
  13973. paramType = castArg->getTypeAsWritten();
  13974. // Copy-initialize a parameter of that type.
  13975. InitializedEntity entity =
  13976. InitializedEntity::InitializeParameter(Context, paramType,
  13977. /*consumed*/ false);
  13978. return PerformCopyInitialization(entity, callLoc, arg);
  13979. }
  13980. static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
  13981. Expr *orig = E;
  13982. unsigned diagID = diag::err_uncasted_use_of_unknown_any;
  13983. while (true) {
  13984. E = E->IgnoreParenImpCasts();
  13985. if (CallExpr *call = dyn_cast<CallExpr>(E)) {
  13986. E = call->getCallee();
  13987. diagID = diag::err_uncasted_call_of_unknown_any;
  13988. } else {
  13989. break;
  13990. }
  13991. }
  13992. SourceLocation loc;
  13993. NamedDecl *d;
  13994. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
  13995. loc = ref->getLocation();
  13996. d = ref->getDecl();
  13997. } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
  13998. loc = mem->getMemberLoc();
  13999. d = mem->getMemberDecl();
  14000. } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
  14001. diagID = diag::err_uncasted_call_of_unknown_any;
  14002. loc = msg->getSelectorStartLoc();
  14003. d = msg->getMethodDecl();
  14004. if (!d) {
  14005. S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
  14006. << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
  14007. << orig->getSourceRange();
  14008. return ExprError();
  14009. }
  14010. } else {
  14011. S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
  14012. << E->getSourceRange();
  14013. return ExprError();
  14014. }
  14015. S.Diag(loc, diagID) << d << orig->getSourceRange();
  14016. // Never recoverable.
  14017. return ExprError();
  14018. }
  14019. /// Check for operands with placeholder types and complain if found.
  14020. /// Returns ExprError() if there was an error and no recovery was possible.
  14021. ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
  14022. if (!getLangOpts().CPlusPlus) {
  14023. // C cannot handle TypoExpr nodes on either side of a binop because it
  14024. // doesn't handle dependent types properly, so make sure any TypoExprs have
  14025. // been dealt with before checking the operands.
  14026. ExprResult Result = CorrectDelayedTyposInExpr(E);
  14027. if (!Result.isUsable()) return ExprError();
  14028. E = Result.get();
  14029. }
  14030. const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
  14031. if (!placeholderType) return E;
  14032. switch (placeholderType->getKind()) {
  14033. // Overloaded expressions.
  14034. case BuiltinType::Overload: {
  14035. // Try to resolve a single function template specialization.
  14036. // This is obligatory.
  14037. ExprResult Result = E;
  14038. if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
  14039. return Result;
  14040. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  14041. // leaves Result unchanged on failure.
  14042. Result = E;
  14043. if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
  14044. return Result;
  14045. // If that failed, try to recover with a call.
  14046. tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
  14047. /*complain*/ true);
  14048. return Result;
  14049. }
  14050. // Bound member functions.
  14051. case BuiltinType::BoundMember: {
  14052. ExprResult result = E;
  14053. const Expr *BME = E->IgnoreParens();
  14054. PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
  14055. // Try to give a nicer diagnostic if it is a bound member that we recognize.
  14056. if (isa<CXXPseudoDestructorExpr>(BME)) {
  14057. PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
  14058. } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
  14059. if (ME->getMemberNameInfo().getName().getNameKind() ==
  14060. DeclarationName::CXXDestructorName)
  14061. PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
  14062. }
  14063. tryToRecoverWithCall(result, PD,
  14064. /*complain*/ true);
  14065. return result;
  14066. }
  14067. // ARC unbridged casts.
  14068. case BuiltinType::ARCUnbridgedCast: {
  14069. Expr *realCast = stripARCUnbridgedCast(E);
  14070. diagnoseARCUnbridgedCast(realCast);
  14071. return realCast;
  14072. }
  14073. // Expressions of unknown type.
  14074. case BuiltinType::UnknownAny:
  14075. return diagnoseUnknownAnyExpr(*this, E);
  14076. // Pseudo-objects.
  14077. case BuiltinType::PseudoObject:
  14078. return checkPseudoObjectRValue(E);
  14079. case BuiltinType::BuiltinFn: {
  14080. // Accept __noop without parens by implicitly converting it to a call expr.
  14081. auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  14082. if (DRE) {
  14083. auto *FD = cast<FunctionDecl>(DRE->getDecl());
  14084. if (FD->getBuiltinID() == Builtin::BI__noop) {
  14085. E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
  14086. CK_BuiltinFnToFnPtr).get();
  14087. return new (Context) CallExpr(Context, E, None, Context.IntTy,
  14088. VK_RValue, SourceLocation());
  14089. }
  14090. }
  14091. Diag(E->getLocStart(), diag::err_builtin_fn_use);
  14092. return ExprError();
  14093. }
  14094. // Expressions of unknown type.
  14095. case BuiltinType::OMPArraySection:
  14096. Diag(E->getLocStart(), diag::err_omp_array_section_use);
  14097. return ExprError();
  14098. // Everything else should be impossible.
  14099. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  14100. case BuiltinType::Id:
  14101. #include "clang/Basic/OpenCLImageTypes.def"
  14102. #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
  14103. #define PLACEHOLDER_TYPE(Id, SingletonId)
  14104. #include "clang/AST/BuiltinTypes.def"
  14105. break;
  14106. }
  14107. llvm_unreachable("invalid placeholder type!");
  14108. }
  14109. bool Sema::CheckCaseExpression(Expr *E) {
  14110. if (E->isTypeDependent())
  14111. return true;
  14112. if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
  14113. return E->getType()->isIntegralOrEnumerationType();
  14114. return false;
  14115. }
  14116. /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
  14117. ExprResult
  14118. Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
  14119. assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
  14120. "Unknown Objective-C Boolean value!");
  14121. QualType BoolT = Context.ObjCBuiltinBoolTy;
  14122. if (!Context.getBOOLDecl()) {
  14123. LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
  14124. Sema::LookupOrdinaryName);
  14125. if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
  14126. NamedDecl *ND = Result.getFoundDecl();
  14127. if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
  14128. Context.setBOOLDecl(TD);
  14129. }
  14130. }
  14131. if (Context.getBOOLDecl())
  14132. BoolT = Context.getBOOLType();
  14133. return new (Context)
  14134. ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
  14135. }
  14136. ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
  14137. llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
  14138. SourceLocation RParen) {
  14139. StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
  14140. auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
  14141. [&](const AvailabilitySpec &Spec) {
  14142. return Spec.getPlatform() == Platform;
  14143. });
  14144. VersionTuple Version;
  14145. if (Spec != AvailSpecs.end())
  14146. Version = Spec->getVersion();
  14147. // The use of `@available` in the enclosing function should be analyzed to
  14148. // warn when it's used inappropriately (i.e. not if(@available)).
  14149. if (getCurFunctionOrMethodDecl())
  14150. getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
  14151. else if (getCurBlock() || getCurLambda())
  14152. getCurFunction()->HasPotentialAvailabilityViolations = true;
  14153. return new (Context)
  14154. ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
  14155. }