SemaChecking.cpp 352 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733
  1. //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
  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 extra semantic analysis beyond what is enforced
  11. // by the C type system.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/SemaInternal.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/CharUnits.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/EvaluatedExprVisitor.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/ExprObjC.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/Analysis/Analyses/FormatString.h"
  26. #include "clang/Basic/CharInfo.h"
  27. #include "clang/Basic/TargetBuiltins.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  30. #include "clang/Sema/Initialization.h"
  31. #include "clang/Sema/Lookup.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "clang/Sema/Sema.h"
  34. #include "llvm/ADT/STLExtras.h"
  35. #include "llvm/ADT/SmallBitVector.h"
  36. #include "llvm/ADT/SmallString.h"
  37. #include "llvm/Support/ConvertUTF.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <limits>
  40. using namespace clang;
  41. using namespace sema;
  42. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  43. unsigned ByteNo) const {
  44. return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
  45. Context.getTargetInfo());
  46. }
  47. /// Checks that a call expression's argument count is the desired number.
  48. /// This is useful when doing custom type-checking. Returns true on error.
  49. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  50. unsigned argCount = call->getNumArgs();
  51. if (argCount == desiredArgCount) return false;
  52. if (argCount < desiredArgCount)
  53. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  54. << 0 /*function call*/ << desiredArgCount << argCount
  55. << call->getSourceRange();
  56. // Highlight all the excess arguments.
  57. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  58. call->getArg(argCount - 1)->getLocEnd());
  59. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  60. << 0 /*function call*/ << desiredArgCount << argCount
  61. << call->getArg(1)->getSourceRange();
  62. }
  63. /// Check that the first argument to __builtin_annotation is an integer
  64. /// and the second argument is a non-wide string literal.
  65. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  66. if (checkArgCount(S, TheCall, 2))
  67. return true;
  68. // First argument should be an integer.
  69. Expr *ValArg = TheCall->getArg(0);
  70. QualType Ty = ValArg->getType();
  71. if (!Ty->isIntegerType()) {
  72. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  73. << ValArg->getSourceRange();
  74. return true;
  75. }
  76. // Second argument should be a constant string.
  77. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  78. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  79. if (!Literal || !Literal->isAscii()) {
  80. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  81. << StrArg->getSourceRange();
  82. return true;
  83. }
  84. TheCall->setType(Ty);
  85. return false;
  86. }
  87. /// Check that the argument to __builtin_addressof is a glvalue, and set the
  88. /// result type to the corresponding pointer type.
  89. static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
  90. if (checkArgCount(S, TheCall, 1))
  91. return true;
  92. ExprResult Arg(TheCall->getArg(0));
  93. QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
  94. if (ResultType.isNull())
  95. return true;
  96. TheCall->setArg(0, Arg.get());
  97. TheCall->setType(ResultType);
  98. return false;
  99. }
  100. static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
  101. CallExpr *TheCall, unsigned SizeIdx,
  102. unsigned DstSizeIdx) {
  103. if (TheCall->getNumArgs() <= SizeIdx ||
  104. TheCall->getNumArgs() <= DstSizeIdx)
  105. return;
  106. const Expr *SizeArg = TheCall->getArg(SizeIdx);
  107. const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
  108. llvm::APSInt Size, DstSize;
  109. // find out if both sizes are known at compile time
  110. if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
  111. !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
  112. return;
  113. if (Size.ule(DstSize))
  114. return;
  115. // confirmed overflow so generate the diagnostic.
  116. IdentifierInfo *FnName = FDecl->getIdentifier();
  117. SourceLocation SL = TheCall->getLocStart();
  118. SourceRange SR = TheCall->getSourceRange();
  119. S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
  120. }
  121. static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
  122. if (checkArgCount(S, BuiltinCall, 2))
  123. return true;
  124. SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
  125. Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
  126. Expr *Call = BuiltinCall->getArg(0);
  127. Expr *Chain = BuiltinCall->getArg(1);
  128. if (Call->getStmtClass() != Stmt::CallExprClass) {
  129. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
  130. << Call->getSourceRange();
  131. return true;
  132. }
  133. auto CE = cast<CallExpr>(Call);
  134. if (CE->getCallee()->getType()->isBlockPointerType()) {
  135. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
  136. << Call->getSourceRange();
  137. return true;
  138. }
  139. const Decl *TargetDecl = CE->getCalleeDecl();
  140. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  141. if (FD->getBuiltinID()) {
  142. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
  143. << Call->getSourceRange();
  144. return true;
  145. }
  146. if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
  147. S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
  148. << Call->getSourceRange();
  149. return true;
  150. }
  151. ExprResult ChainResult = S.UsualUnaryConversions(Chain);
  152. if (ChainResult.isInvalid())
  153. return true;
  154. if (!ChainResult.get()->getType()->isPointerType()) {
  155. S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
  156. << Chain->getSourceRange();
  157. return true;
  158. }
  159. QualType ReturnTy = CE->getCallReturnType(S.Context);
  160. QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
  161. QualType BuiltinTy = S.Context.getFunctionType(
  162. ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo(),
  163. None); // HLSL Change - builtins are all in parameters
  164. QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
  165. Builtin =
  166. S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
  167. BuiltinCall->setType(CE->getType());
  168. BuiltinCall->setValueKind(CE->getValueKind());
  169. BuiltinCall->setObjectKind(CE->getObjectKind());
  170. BuiltinCall->setCallee(Builtin);
  171. BuiltinCall->setArg(1, ChainResult.get());
  172. return false;
  173. }
  174. static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
  175. Scope::ScopeFlags NeededScopeFlags,
  176. unsigned DiagID) {
  177. // Scopes aren't available during instantiation. Fortunately, builtin
  178. // functions cannot be template args so they cannot be formed through template
  179. // instantiation. Therefore checking once during the parse is sufficient.
  180. if (!SemaRef.ActiveTemplateInstantiations.empty())
  181. return false;
  182. Scope *S = SemaRef.getCurScope();
  183. while (S && !S->isSEHExceptScope())
  184. S = S->getParent();
  185. if (!S || !(S->getFlags() & NeededScopeFlags)) {
  186. auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  187. SemaRef.Diag(TheCall->getExprLoc(), DiagID)
  188. << DRE->getDecl()->getIdentifier();
  189. return true;
  190. }
  191. return false;
  192. }
  193. ExprResult
  194. Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
  195. CallExpr *TheCall) {
  196. ExprResult TheCallResult(TheCall);
  197. // Find out if any arguments are required to be integer constant expressions.
  198. unsigned ICEArguments = 0;
  199. ASTContext::GetBuiltinTypeError Error;
  200. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  201. if (Error != ASTContext::GE_None)
  202. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  203. // If any arguments are required to be ICE's, check and diagnose.
  204. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  205. // Skip arguments not required to be ICE's.
  206. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  207. llvm::APSInt Result;
  208. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  209. return true;
  210. ICEArguments &= ~(1 << ArgNo);
  211. }
  212. switch (BuiltinID) {
  213. case Builtin::BI__builtin___CFStringMakeConstantString:
  214. assert(TheCall->getNumArgs() == 1 &&
  215. "Wrong # arguments to builtin CFStringMakeConstantString");
  216. if (CheckObjCString(TheCall->getArg(0)))
  217. return ExprError();
  218. break;
  219. case Builtin::BI__builtin_stdarg_start:
  220. case Builtin::BI__builtin_va_start:
  221. if (SemaBuiltinVAStart(TheCall))
  222. return ExprError();
  223. break;
  224. case Builtin::BI__va_start: {
  225. switch (Context.getTargetInfo().getTriple().getArch()) {
  226. case llvm::Triple::arm:
  227. case llvm::Triple::thumb:
  228. if (SemaBuiltinVAStartARM(TheCall))
  229. return ExprError();
  230. break;
  231. default:
  232. if (SemaBuiltinVAStart(TheCall))
  233. return ExprError();
  234. break;
  235. }
  236. break;
  237. }
  238. case Builtin::BI__builtin_isgreater:
  239. case Builtin::BI__builtin_isgreaterequal:
  240. case Builtin::BI__builtin_isless:
  241. case Builtin::BI__builtin_islessequal:
  242. case Builtin::BI__builtin_islessgreater:
  243. case Builtin::BI__builtin_isunordered:
  244. if (SemaBuiltinUnorderedCompare(TheCall))
  245. return ExprError();
  246. break;
  247. case Builtin::BI__builtin_fpclassify:
  248. if (SemaBuiltinFPClassification(TheCall, 6))
  249. return ExprError();
  250. break;
  251. case Builtin::BI__builtin_isfinite:
  252. case Builtin::BI__builtin_isinf:
  253. case Builtin::BI__builtin_isinf_sign:
  254. case Builtin::BI__builtin_isnan:
  255. case Builtin::BI__builtin_isnormal:
  256. if (SemaBuiltinFPClassification(TheCall, 1))
  257. return ExprError();
  258. break;
  259. case Builtin::BI__builtin_shufflevector:
  260. return SemaBuiltinShuffleVector(TheCall);
  261. // TheCall will be freed by the smart pointer here, but that's fine, since
  262. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  263. case Builtin::BI__builtin_prefetch:
  264. if (SemaBuiltinPrefetch(TheCall))
  265. return ExprError();
  266. break;
  267. case Builtin::BI__assume:
  268. case Builtin::BI__builtin_assume:
  269. if (SemaBuiltinAssume(TheCall))
  270. return ExprError();
  271. break;
  272. case Builtin::BI__builtin_assume_aligned:
  273. if (SemaBuiltinAssumeAligned(TheCall))
  274. return ExprError();
  275. break;
  276. case Builtin::BI__builtin_object_size:
  277. if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
  278. return ExprError();
  279. break;
  280. case Builtin::BI__builtin_longjmp:
  281. if (SemaBuiltinLongjmp(TheCall))
  282. return ExprError();
  283. break;
  284. case Builtin::BI__builtin_setjmp:
  285. if (SemaBuiltinSetjmp(TheCall))
  286. return ExprError();
  287. break;
  288. case Builtin::BI_setjmp:
  289. case Builtin::BI_setjmpex:
  290. if (checkArgCount(*this, TheCall, 1))
  291. return true;
  292. break;
  293. case Builtin::BI__builtin_classify_type:
  294. if (checkArgCount(*this, TheCall, 1)) return true;
  295. TheCall->setType(Context.IntTy);
  296. break;
  297. case Builtin::BI__builtin_constant_p:
  298. if (checkArgCount(*this, TheCall, 1)) return true;
  299. TheCall->setType(Context.IntTy);
  300. break;
  301. case Builtin::BI__sync_fetch_and_add:
  302. case Builtin::BI__sync_fetch_and_add_1:
  303. case Builtin::BI__sync_fetch_and_add_2:
  304. case Builtin::BI__sync_fetch_and_add_4:
  305. case Builtin::BI__sync_fetch_and_add_8:
  306. case Builtin::BI__sync_fetch_and_add_16:
  307. case Builtin::BI__sync_fetch_and_sub:
  308. case Builtin::BI__sync_fetch_and_sub_1:
  309. case Builtin::BI__sync_fetch_and_sub_2:
  310. case Builtin::BI__sync_fetch_and_sub_4:
  311. case Builtin::BI__sync_fetch_and_sub_8:
  312. case Builtin::BI__sync_fetch_and_sub_16:
  313. case Builtin::BI__sync_fetch_and_or:
  314. case Builtin::BI__sync_fetch_and_or_1:
  315. case Builtin::BI__sync_fetch_and_or_2:
  316. case Builtin::BI__sync_fetch_and_or_4:
  317. case Builtin::BI__sync_fetch_and_or_8:
  318. case Builtin::BI__sync_fetch_and_or_16:
  319. case Builtin::BI__sync_fetch_and_and:
  320. case Builtin::BI__sync_fetch_and_and_1:
  321. case Builtin::BI__sync_fetch_and_and_2:
  322. case Builtin::BI__sync_fetch_and_and_4:
  323. case Builtin::BI__sync_fetch_and_and_8:
  324. case Builtin::BI__sync_fetch_and_and_16:
  325. case Builtin::BI__sync_fetch_and_xor:
  326. case Builtin::BI__sync_fetch_and_xor_1:
  327. case Builtin::BI__sync_fetch_and_xor_2:
  328. case Builtin::BI__sync_fetch_and_xor_4:
  329. case Builtin::BI__sync_fetch_and_xor_8:
  330. case Builtin::BI__sync_fetch_and_xor_16:
  331. case Builtin::BI__sync_fetch_and_nand:
  332. case Builtin::BI__sync_fetch_and_nand_1:
  333. case Builtin::BI__sync_fetch_and_nand_2:
  334. case Builtin::BI__sync_fetch_and_nand_4:
  335. case Builtin::BI__sync_fetch_and_nand_8:
  336. case Builtin::BI__sync_fetch_and_nand_16:
  337. case Builtin::BI__sync_add_and_fetch:
  338. case Builtin::BI__sync_add_and_fetch_1:
  339. case Builtin::BI__sync_add_and_fetch_2:
  340. case Builtin::BI__sync_add_and_fetch_4:
  341. case Builtin::BI__sync_add_and_fetch_8:
  342. case Builtin::BI__sync_add_and_fetch_16:
  343. case Builtin::BI__sync_sub_and_fetch:
  344. case Builtin::BI__sync_sub_and_fetch_1:
  345. case Builtin::BI__sync_sub_and_fetch_2:
  346. case Builtin::BI__sync_sub_and_fetch_4:
  347. case Builtin::BI__sync_sub_and_fetch_8:
  348. case Builtin::BI__sync_sub_and_fetch_16:
  349. case Builtin::BI__sync_and_and_fetch:
  350. case Builtin::BI__sync_and_and_fetch_1:
  351. case Builtin::BI__sync_and_and_fetch_2:
  352. case Builtin::BI__sync_and_and_fetch_4:
  353. case Builtin::BI__sync_and_and_fetch_8:
  354. case Builtin::BI__sync_and_and_fetch_16:
  355. case Builtin::BI__sync_or_and_fetch:
  356. case Builtin::BI__sync_or_and_fetch_1:
  357. case Builtin::BI__sync_or_and_fetch_2:
  358. case Builtin::BI__sync_or_and_fetch_4:
  359. case Builtin::BI__sync_or_and_fetch_8:
  360. case Builtin::BI__sync_or_and_fetch_16:
  361. case Builtin::BI__sync_xor_and_fetch:
  362. case Builtin::BI__sync_xor_and_fetch_1:
  363. case Builtin::BI__sync_xor_and_fetch_2:
  364. case Builtin::BI__sync_xor_and_fetch_4:
  365. case Builtin::BI__sync_xor_and_fetch_8:
  366. case Builtin::BI__sync_xor_and_fetch_16:
  367. case Builtin::BI__sync_nand_and_fetch:
  368. case Builtin::BI__sync_nand_and_fetch_1:
  369. case Builtin::BI__sync_nand_and_fetch_2:
  370. case Builtin::BI__sync_nand_and_fetch_4:
  371. case Builtin::BI__sync_nand_and_fetch_8:
  372. case Builtin::BI__sync_nand_and_fetch_16:
  373. case Builtin::BI__sync_val_compare_and_swap:
  374. case Builtin::BI__sync_val_compare_and_swap_1:
  375. case Builtin::BI__sync_val_compare_and_swap_2:
  376. case Builtin::BI__sync_val_compare_and_swap_4:
  377. case Builtin::BI__sync_val_compare_and_swap_8:
  378. case Builtin::BI__sync_val_compare_and_swap_16:
  379. case Builtin::BI__sync_bool_compare_and_swap:
  380. case Builtin::BI__sync_bool_compare_and_swap_1:
  381. case Builtin::BI__sync_bool_compare_and_swap_2:
  382. case Builtin::BI__sync_bool_compare_and_swap_4:
  383. case Builtin::BI__sync_bool_compare_and_swap_8:
  384. case Builtin::BI__sync_bool_compare_and_swap_16:
  385. case Builtin::BI__sync_lock_test_and_set:
  386. case Builtin::BI__sync_lock_test_and_set_1:
  387. case Builtin::BI__sync_lock_test_and_set_2:
  388. case Builtin::BI__sync_lock_test_and_set_4:
  389. case Builtin::BI__sync_lock_test_and_set_8:
  390. case Builtin::BI__sync_lock_test_and_set_16:
  391. case Builtin::BI__sync_lock_release:
  392. case Builtin::BI__sync_lock_release_1:
  393. case Builtin::BI__sync_lock_release_2:
  394. case Builtin::BI__sync_lock_release_4:
  395. case Builtin::BI__sync_lock_release_8:
  396. case Builtin::BI__sync_lock_release_16:
  397. case Builtin::BI__sync_swap:
  398. case Builtin::BI__sync_swap_1:
  399. case Builtin::BI__sync_swap_2:
  400. case Builtin::BI__sync_swap_4:
  401. case Builtin::BI__sync_swap_8:
  402. case Builtin::BI__sync_swap_16:
  403. return SemaBuiltinAtomicOverloaded(TheCallResult);
  404. #define BUILTIN(ID, TYPE, ATTRS)
  405. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  406. case Builtin::BI##ID: \
  407. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  408. #include "clang/Basic/Builtins.def"
  409. case Builtin::BI__builtin_annotation:
  410. if (SemaBuiltinAnnotation(*this, TheCall))
  411. return ExprError();
  412. break;
  413. case Builtin::BI__builtin_addressof:
  414. if (SemaBuiltinAddressof(*this, TheCall))
  415. return ExprError();
  416. break;
  417. case Builtin::BI__builtin_operator_new:
  418. case Builtin::BI__builtin_operator_delete:
  419. if (!getLangOpts().CPlusPlus) {
  420. Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
  421. << (BuiltinID == Builtin::BI__builtin_operator_new
  422. ? "__builtin_operator_new"
  423. : "__builtin_operator_delete")
  424. << "C++";
  425. return ExprError();
  426. }
  427. // CodeGen assumes it can find the global new and delete to call,
  428. // so ensure that they are declared.
  429. DeclareGlobalNewDelete();
  430. break;
  431. // check secure string manipulation functions where overflows
  432. // are detectable at compile time
  433. case Builtin::BI__builtin___memcpy_chk:
  434. case Builtin::BI__builtin___memmove_chk:
  435. case Builtin::BI__builtin___memset_chk:
  436. case Builtin::BI__builtin___strlcat_chk:
  437. case Builtin::BI__builtin___strlcpy_chk:
  438. case Builtin::BI__builtin___strncat_chk:
  439. case Builtin::BI__builtin___strncpy_chk:
  440. case Builtin::BI__builtin___stpncpy_chk:
  441. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
  442. break;
  443. case Builtin::BI__builtin___memccpy_chk:
  444. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
  445. break;
  446. case Builtin::BI__builtin___snprintf_chk:
  447. case Builtin::BI__builtin___vsnprintf_chk:
  448. SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
  449. break;
  450. case Builtin::BI__builtin_call_with_static_chain:
  451. if (SemaBuiltinCallWithStaticChain(*this, TheCall))
  452. return ExprError();
  453. break;
  454. case Builtin::BI__exception_code:
  455. case Builtin::BI_exception_code: {
  456. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
  457. diag::err_seh___except_block))
  458. return ExprError();
  459. break;
  460. }
  461. case Builtin::BI__exception_info:
  462. case Builtin::BI_exception_info: {
  463. if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
  464. diag::err_seh___except_filter))
  465. return ExprError();
  466. break;
  467. }
  468. case Builtin::BI__GetExceptionInfo:
  469. if (checkArgCount(*this, TheCall, 1))
  470. return ExprError();
  471. if (CheckCXXThrowOperand(
  472. TheCall->getLocStart(),
  473. Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
  474. TheCall))
  475. return ExprError();
  476. TheCall->setType(Context.VoidPtrTy);
  477. break;
  478. }
  479. // Since the target specific builtins for each arch overlap, only check those
  480. // of the arch we are compiling for.
  481. #if 0 // HLSL Change Starts
  482. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  483. switch (Context.getTargetInfo().getTriple().getArch()) {
  484. case llvm::Triple::arm:
  485. case llvm::Triple::armeb:
  486. case llvm::Triple::thumb:
  487. case llvm::Triple::thumbeb:
  488. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  489. return ExprError();
  490. break;
  491. case llvm::Triple::aarch64:
  492. case llvm::Triple::aarch64_be:
  493. if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
  494. return ExprError();
  495. break;
  496. case llvm::Triple::mips:
  497. case llvm::Triple::mipsel:
  498. case llvm::Triple::mips64:
  499. case llvm::Triple::mips64el:
  500. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  501. return ExprError();
  502. break;
  503. case llvm::Triple::systemz:
  504. if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
  505. return ExprError();
  506. break;
  507. case llvm::Triple::x86:
  508. case llvm::Triple::x86_64:
  509. if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
  510. return ExprError();
  511. break;
  512. case llvm::Triple::ppc:
  513. case llvm::Triple::ppc64:
  514. case llvm::Triple::ppc64le:
  515. if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
  516. return ExprError();
  517. break;
  518. default:
  519. break;
  520. }
  521. }
  522. #endif // HLSL Change Ends
  523. return TheCallResult;
  524. }
  525. #if 0 // HLSL Change Starts
  526. // Get the valid immediate range for the specified NEON type code.
  527. static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
  528. NeonTypeFlags Type(t);
  529. int IsQuad = ForceQuad ? true : Type.isQuad();
  530. switch (Type.getEltType()) {
  531. case NeonTypeFlags::Int8:
  532. case NeonTypeFlags::Poly8:
  533. return shift ? 7 : (8 << IsQuad) - 1;
  534. case NeonTypeFlags::Int16:
  535. case NeonTypeFlags::Poly16:
  536. return shift ? 15 : (4 << IsQuad) - 1;
  537. case NeonTypeFlags::Int32:
  538. return shift ? 31 : (2 << IsQuad) - 1;
  539. case NeonTypeFlags::Int64:
  540. case NeonTypeFlags::Poly64:
  541. return shift ? 63 : (1 << IsQuad) - 1;
  542. case NeonTypeFlags::Poly128:
  543. return shift ? 127 : (1 << IsQuad) - 1;
  544. case NeonTypeFlags::Float16:
  545. assert(!shift && "cannot shift float types!");
  546. return (4 << IsQuad) - 1;
  547. case NeonTypeFlags::Float32:
  548. assert(!shift && "cannot shift float types!");
  549. return (2 << IsQuad) - 1;
  550. case NeonTypeFlags::Float64:
  551. assert(!shift && "cannot shift float types!");
  552. return (1 << IsQuad) - 1;
  553. }
  554. llvm_unreachable("Invalid NeonTypeFlag!");
  555. }
  556. /// getNeonEltType - Return the QualType corresponding to the elements of
  557. /// the vector type specified by the NeonTypeFlags. This is used to check
  558. /// the pointer arguments for Neon load/store intrinsics.
  559. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
  560. bool IsPolyUnsigned, bool IsInt64Long) {
  561. switch (Flags.getEltType()) {
  562. case NeonTypeFlags::Int8:
  563. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  564. case NeonTypeFlags::Int16:
  565. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  566. case NeonTypeFlags::Int32:
  567. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  568. case NeonTypeFlags::Int64:
  569. if (IsInt64Long)
  570. return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
  571. else
  572. return Flags.isUnsigned() ? Context.UnsignedLongLongTy
  573. : Context.LongLongTy;
  574. case NeonTypeFlags::Poly8:
  575. return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
  576. case NeonTypeFlags::Poly16:
  577. return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
  578. case NeonTypeFlags::Poly64:
  579. if (IsInt64Long)
  580. return Context.UnsignedLongTy;
  581. else
  582. return Context.UnsignedLongLongTy;
  583. case NeonTypeFlags::Poly128:
  584. break;
  585. case NeonTypeFlags::Float16:
  586. return Context.HalfTy;
  587. case NeonTypeFlags::Float32:
  588. return Context.FloatTy;
  589. case NeonTypeFlags::Float64:
  590. return Context.DoubleTy;
  591. }
  592. llvm_unreachable("Invalid NeonTypeFlag!");
  593. }
  594. bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  595. llvm::APSInt Result;
  596. uint64_t mask = 0;
  597. unsigned TV = 0;
  598. int PtrArgNum = -1;
  599. bool HasConstPtr = false;
  600. switch (BuiltinID) {
  601. #define GET_NEON_OVERLOAD_CHECK
  602. #include "clang/Basic/arm_neon.inc"
  603. #undef GET_NEON_OVERLOAD_CHECK
  604. }
  605. // For NEON intrinsics which are overloaded on vector element type, validate
  606. // the immediate which specifies which variant to emit.
  607. unsigned ImmArg = TheCall->getNumArgs()-1;
  608. if (mask) {
  609. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  610. return true;
  611. TV = Result.getLimitedValue(64);
  612. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  613. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  614. << TheCall->getArg(ImmArg)->getSourceRange();
  615. }
  616. if (PtrArgNum >= 0) {
  617. // Check that pointer arguments have the specified type.
  618. Expr *Arg = TheCall->getArg(PtrArgNum);
  619. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  620. Arg = ICE->getSubExpr();
  621. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  622. QualType RHSTy = RHS.get()->getType();
  623. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  624. bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
  625. bool IsInt64Long =
  626. Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
  627. QualType EltTy =
  628. getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
  629. if (HasConstPtr)
  630. EltTy = EltTy.withConst();
  631. QualType LHSTy = Context.getPointerType(EltTy);
  632. AssignConvertType ConvTy;
  633. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  634. if (RHS.isInvalid())
  635. return true;
  636. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  637. RHS.get(), AA_Assigning))
  638. return true;
  639. }
  640. // For NEON intrinsics which take an immediate value as part of the
  641. // instruction, range check them here.
  642. unsigned i = 0, l = 0, u = 0;
  643. switch (BuiltinID) {
  644. default:
  645. return false;
  646. #define GET_NEON_IMMEDIATE_CHECK
  647. #include "clang/Basic/arm_neon.inc"
  648. #undef GET_NEON_IMMEDIATE_CHECK
  649. }
  650. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  651. }
  652. bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
  653. unsigned MaxWidth) {
  654. assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
  655. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  656. BuiltinID == ARM::BI__builtin_arm_strex ||
  657. BuiltinID == ARM::BI__builtin_arm_stlex ||
  658. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  659. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  660. BuiltinID == AArch64::BI__builtin_arm_strex ||
  661. BuiltinID == AArch64::BI__builtin_arm_stlex) &&
  662. "unexpected ARM builtin");
  663. bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
  664. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  665. BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  666. BuiltinID == AArch64::BI__builtin_arm_ldaex;
  667. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  668. // Ensure that we have the proper number of arguments.
  669. if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
  670. return true;
  671. // Inspect the pointer argument of the atomic builtin. This should always be
  672. // a pointer type, whose element is an integral scalar or pointer type.
  673. // Because it is a pointer type, we don't have to worry about any implicit
  674. // casts here.
  675. Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
  676. ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
  677. if (PointerArgRes.isInvalid())
  678. return true;
  679. PointerArg = PointerArgRes.get();
  680. const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
  681. if (!pointerType) {
  682. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  683. << PointerArg->getType() << PointerArg->getSourceRange();
  684. return true;
  685. }
  686. // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
  687. // task is to insert the appropriate casts into the AST. First work out just
  688. // what the appropriate type is.
  689. QualType ValType = pointerType->getPointeeType();
  690. QualType AddrType = ValType.getUnqualifiedType().withVolatile();
  691. if (IsLdrex)
  692. AddrType.addConst();
  693. // Issue a warning if the cast is dodgy.
  694. CastKind CastNeeded = CK_NoOp;
  695. if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
  696. CastNeeded = CK_BitCast;
  697. Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
  698. << PointerArg->getType()
  699. << Context.getPointerType(AddrType)
  700. << AA_Passing << PointerArg->getSourceRange();
  701. }
  702. // Finally, do the cast and replace the argument with the corrected version.
  703. AddrType = Context.getPointerType(AddrType);
  704. PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
  705. if (PointerArgRes.isInvalid())
  706. return true;
  707. PointerArg = PointerArgRes.get();
  708. TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
  709. // In general, we allow ints, floats and pointers to be loaded and stored.
  710. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  711. !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
  712. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
  713. << PointerArg->getType() << PointerArg->getSourceRange();
  714. return true;
  715. }
  716. // But ARM doesn't have instructions to deal with 128-bit versions.
  717. if (Context.getTypeSize(ValType) > MaxWidth) {
  718. assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
  719. Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
  720. << PointerArg->getType() << PointerArg->getSourceRange();
  721. return true;
  722. }
  723. switch (ValType.getObjCLifetime()) {
  724. case Qualifiers::OCL_None:
  725. case Qualifiers::OCL_ExplicitNone:
  726. // okay
  727. break;
  728. case Qualifiers::OCL_Weak:
  729. case Qualifiers::OCL_Strong:
  730. case Qualifiers::OCL_Autoreleasing:
  731. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  732. << ValType << PointerArg->getSourceRange();
  733. return true;
  734. }
  735. if (IsLdrex) {
  736. TheCall->setType(ValType);
  737. return false;
  738. }
  739. // Initialize the argument to be stored.
  740. ExprResult ValArg = TheCall->getArg(0);
  741. InitializedEntity Entity = InitializedEntity::InitializeParameter(
  742. Context, ValType, /*consume*/ false);
  743. ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
  744. if (ValArg.isInvalid())
  745. return true;
  746. TheCall->setArg(0, ValArg.get());
  747. // __builtin_arm_strex always returns an int. It's marked as such in the .def,
  748. // but the custom checker bypasses all default analysis.
  749. TheCall->setType(Context.IntTy);
  750. return false;
  751. }
  752. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  753. llvm::APSInt Result;
  754. if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
  755. BuiltinID == ARM::BI__builtin_arm_ldaex ||
  756. BuiltinID == ARM::BI__builtin_arm_strex ||
  757. BuiltinID == ARM::BI__builtin_arm_stlex) {
  758. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
  759. }
  760. if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
  761. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  762. SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
  763. }
  764. if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  765. BuiltinID == ARM::BI__builtin_arm_wsr64)
  766. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
  767. if (BuiltinID == ARM::BI__builtin_arm_rsr ||
  768. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  769. BuiltinID == ARM::BI__builtin_arm_wsr ||
  770. BuiltinID == ARM::BI__builtin_arm_wsrp)
  771. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  772. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  773. return true;
  774. // For intrinsics which take an immediate value as part of the instruction,
  775. // range check them here.
  776. unsigned i = 0, l = 0, u = 0;
  777. switch (BuiltinID) {
  778. default: return false;
  779. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  780. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  781. case ARM::BI__builtin_arm_vcvtr_f:
  782. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  783. case ARM::BI__builtin_arm_dmb:
  784. case ARM::BI__builtin_arm_dsb:
  785. case ARM::BI__builtin_arm_isb:
  786. case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
  787. }
  788. // FIXME: VFP Intrinsics should error if VFP not present.
  789. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  790. }
  791. bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
  792. CallExpr *TheCall) {
  793. llvm::APSInt Result;
  794. if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
  795. BuiltinID == AArch64::BI__builtin_arm_ldaex ||
  796. BuiltinID == AArch64::BI__builtin_arm_strex ||
  797. BuiltinID == AArch64::BI__builtin_arm_stlex) {
  798. return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
  799. }
  800. if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
  801. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  802. SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
  803. SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
  804. SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
  805. }
  806. if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  807. BuiltinID == AArch64::BI__builtin_arm_wsr64)
  808. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
  809. if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
  810. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  811. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  812. BuiltinID == AArch64::BI__builtin_arm_wsrp)
  813. return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
  814. if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
  815. return true;
  816. // For intrinsics which take an immediate value as part of the instruction,
  817. // range check them here.
  818. unsigned i = 0, l = 0, u = 0;
  819. switch (BuiltinID) {
  820. default: return false;
  821. case AArch64::BI__builtin_arm_dmb:
  822. case AArch64::BI__builtin_arm_dsb:
  823. case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
  824. }
  825. return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
  826. }
  827. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  828. unsigned i = 0, l = 0, u = 0;
  829. switch (BuiltinID) {
  830. default: return false;
  831. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  832. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  833. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  834. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  835. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  836. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  837. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  838. }
  839. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  840. }
  841. bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  842. unsigned i = 0, l = 0, u = 0;
  843. bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
  844. BuiltinID == PPC::BI__builtin_divdeu ||
  845. BuiltinID == PPC::BI__builtin_bpermd;
  846. bool IsTarget64Bit = Context.getTargetInfo()
  847. .getTypeWidth(Context
  848. .getTargetInfo()
  849. .getIntPtrType()) == 64;
  850. bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
  851. BuiltinID == PPC::BI__builtin_divweu ||
  852. BuiltinID == PPC::BI__builtin_divde ||
  853. BuiltinID == PPC::BI__builtin_divdeu;
  854. if (Is64BitBltin && !IsTarget64Bit)
  855. return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
  856. << TheCall->getSourceRange();
  857. if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
  858. (BuiltinID == PPC::BI__builtin_bpermd &&
  859. !Context.getTargetInfo().hasFeature("bpermd")))
  860. return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
  861. << TheCall->getSourceRange();
  862. switch (BuiltinID) {
  863. default: return false;
  864. case PPC::BI__builtin_altivec_crypto_vshasigmaw:
  865. case PPC::BI__builtin_altivec_crypto_vshasigmad:
  866. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
  867. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  868. case PPC::BI__builtin_tbegin:
  869. case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
  870. case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
  871. case PPC::BI__builtin_tabortwc:
  872. case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
  873. case PPC::BI__builtin_tabortwci:
  874. case PPC::BI__builtin_tabortdci:
  875. return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
  876. SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
  877. }
  878. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  879. }
  880. bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
  881. CallExpr *TheCall) {
  882. if (BuiltinID == SystemZ::BI__builtin_tabort) {
  883. Expr *Arg = TheCall->getArg(0);
  884. llvm::APSInt AbortCode(32);
  885. if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
  886. AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
  887. return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
  888. << Arg->getSourceRange();
  889. }
  890. // For intrinsics which take an immediate value as part of the instruction,
  891. // range check them here.
  892. unsigned i = 0, l = 0, u = 0;
  893. switch (BuiltinID) {
  894. default: return false;
  895. case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
  896. case SystemZ::BI__builtin_s390_verimb:
  897. case SystemZ::BI__builtin_s390_verimh:
  898. case SystemZ::BI__builtin_s390_verimf:
  899. case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
  900. case SystemZ::BI__builtin_s390_vfaeb:
  901. case SystemZ::BI__builtin_s390_vfaeh:
  902. case SystemZ::BI__builtin_s390_vfaef:
  903. case SystemZ::BI__builtin_s390_vfaebs:
  904. case SystemZ::BI__builtin_s390_vfaehs:
  905. case SystemZ::BI__builtin_s390_vfaefs:
  906. case SystemZ::BI__builtin_s390_vfaezb:
  907. case SystemZ::BI__builtin_s390_vfaezh:
  908. case SystemZ::BI__builtin_s390_vfaezf:
  909. case SystemZ::BI__builtin_s390_vfaezbs:
  910. case SystemZ::BI__builtin_s390_vfaezhs:
  911. case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
  912. case SystemZ::BI__builtin_s390_vfidb:
  913. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
  914. SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
  915. case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
  916. case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
  917. case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
  918. case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
  919. case SystemZ::BI__builtin_s390_vstrcb:
  920. case SystemZ::BI__builtin_s390_vstrch:
  921. case SystemZ::BI__builtin_s390_vstrcf:
  922. case SystemZ::BI__builtin_s390_vstrczb:
  923. case SystemZ::BI__builtin_s390_vstrczh:
  924. case SystemZ::BI__builtin_s390_vstrczf:
  925. case SystemZ::BI__builtin_s390_vstrcbs:
  926. case SystemZ::BI__builtin_s390_vstrchs:
  927. case SystemZ::BI__builtin_s390_vstrcfs:
  928. case SystemZ::BI__builtin_s390_vstrczbs:
  929. case SystemZ::BI__builtin_s390_vstrczhs:
  930. case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
  931. }
  932. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  933. }
  934. bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  935. unsigned i = 0, l = 0, u = 0;
  936. switch (BuiltinID) {
  937. default: return false;
  938. case X86::BI__builtin_cpu_supports:
  939. return SemaBuiltinCpuSupports(TheCall);
  940. case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
  941. case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
  942. case X86::BI__builtin_ia32_vpermil2pd:
  943. case X86::BI__builtin_ia32_vpermil2pd256:
  944. case X86::BI__builtin_ia32_vpermil2ps:
  945. case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
  946. case X86::BI__builtin_ia32_cmpb128_mask:
  947. case X86::BI__builtin_ia32_cmpw128_mask:
  948. case X86::BI__builtin_ia32_cmpd128_mask:
  949. case X86::BI__builtin_ia32_cmpq128_mask:
  950. case X86::BI__builtin_ia32_cmpb256_mask:
  951. case X86::BI__builtin_ia32_cmpw256_mask:
  952. case X86::BI__builtin_ia32_cmpd256_mask:
  953. case X86::BI__builtin_ia32_cmpq256_mask:
  954. case X86::BI__builtin_ia32_cmpb512_mask:
  955. case X86::BI__builtin_ia32_cmpw512_mask:
  956. case X86::BI__builtin_ia32_cmpd512_mask:
  957. case X86::BI__builtin_ia32_cmpq512_mask:
  958. case X86::BI__builtin_ia32_ucmpb128_mask:
  959. case X86::BI__builtin_ia32_ucmpw128_mask:
  960. case X86::BI__builtin_ia32_ucmpd128_mask:
  961. case X86::BI__builtin_ia32_ucmpq128_mask:
  962. case X86::BI__builtin_ia32_ucmpb256_mask:
  963. case X86::BI__builtin_ia32_ucmpw256_mask:
  964. case X86::BI__builtin_ia32_ucmpd256_mask:
  965. case X86::BI__builtin_ia32_ucmpq256_mask:
  966. case X86::BI__builtin_ia32_ucmpb512_mask:
  967. case X86::BI__builtin_ia32_ucmpw512_mask:
  968. case X86::BI__builtin_ia32_ucmpd512_mask:
  969. case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
  970. case X86::BI__builtin_ia32_roundps:
  971. case X86::BI__builtin_ia32_roundpd:
  972. case X86::BI__builtin_ia32_roundps256:
  973. case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
  974. case X86::BI__builtin_ia32_roundss:
  975. case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
  976. case X86::BI__builtin_ia32_cmpps:
  977. case X86::BI__builtin_ia32_cmpss:
  978. case X86::BI__builtin_ia32_cmppd:
  979. case X86::BI__builtin_ia32_cmpsd:
  980. case X86::BI__builtin_ia32_cmpps256:
  981. case X86::BI__builtin_ia32_cmppd256:
  982. case X86::BI__builtin_ia32_cmpps512_mask:
  983. case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
  984. case X86::BI__builtin_ia32_vpcomub:
  985. case X86::BI__builtin_ia32_vpcomuw:
  986. case X86::BI__builtin_ia32_vpcomud:
  987. case X86::BI__builtin_ia32_vpcomuq:
  988. case X86::BI__builtin_ia32_vpcomb:
  989. case X86::BI__builtin_ia32_vpcomw:
  990. case X86::BI__builtin_ia32_vpcomd:
  991. case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
  992. }
  993. return SemaBuiltinConstantArgRange(TheCall, i, l, u);
  994. }
  995. #endif // HLSL Change Ends
  996. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  997. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  998. /// Returns true when the format fits the function and the FormatStringInfo has
  999. /// been populated.
  1000. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  1001. FormatStringInfo *FSI) {
  1002. FSI->HasVAListArg = Format->getFirstArg() == 0;
  1003. FSI->FormatIdx = Format->getFormatIdx() - 1;
  1004. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  1005. // The way the format attribute works in GCC, the implicit this argument
  1006. // of member functions is counted. However, it doesn't appear in our own
  1007. // lists, so decrement format_idx in that case.
  1008. if (IsCXXMember) {
  1009. if(FSI->FormatIdx == 0)
  1010. return false;
  1011. --FSI->FormatIdx;
  1012. if (FSI->FirstDataArg != 0)
  1013. --FSI->FirstDataArg;
  1014. }
  1015. return true;
  1016. }
  1017. /// Checks if a the given expression evaluates to null.
  1018. ///
  1019. /// \brief Returns true if the value evaluates to null.
  1020. static bool CheckNonNullExpr(Sema &S,
  1021. const Expr *Expr) {
  1022. // If the expression has non-null type, it doesn't evaluate to null.
  1023. if (auto nullability
  1024. = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
  1025. if (*nullability == NullabilityKind::NonNull)
  1026. return false;
  1027. }
  1028. // As a special case, transparent unions initialized with zero are
  1029. // considered null for the purposes of the nonnull attribute.
  1030. if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
  1031. if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
  1032. if (const CompoundLiteralExpr *CLE =
  1033. dyn_cast<CompoundLiteralExpr>(Expr))
  1034. if (const InitListExpr *ILE =
  1035. dyn_cast<InitListExpr>(CLE->getInitializer()))
  1036. Expr = ILE->getInit(0);
  1037. }
  1038. bool Result;
  1039. return (!Expr->isValueDependent() &&
  1040. Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
  1041. !Result);
  1042. }
  1043. static void CheckNonNullArgument(Sema &S,
  1044. const Expr *ArgExpr,
  1045. SourceLocation CallSiteLoc) {
  1046. if (CheckNonNullExpr(S, ArgExpr))
  1047. S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1048. }
  1049. bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
  1050. #if 0 // HLSL Change Starts
  1051. FormatStringInfo FSI;
  1052. if ((GetFormatStringType(Format) == FST_NSString) &&
  1053. getFormatStringInfo(Format, false, &FSI)) {
  1054. Idx = FSI.FormatIdx;
  1055. return true;
  1056. }
  1057. #endif // HLSL Change Ends
  1058. return false;
  1059. }
  1060. #if 0 // HLSL Change Starts
  1061. /// \brief Diagnose use of %s directive in an NSString which is being passed
  1062. /// as formatting string to formatting method.
  1063. static void
  1064. DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
  1065. const NamedDecl *FDecl,
  1066. Expr **Args,
  1067. unsigned NumArgs) {
  1068. unsigned Idx = 0;
  1069. bool Format = false;
  1070. ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
  1071. if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
  1072. Idx = 2;
  1073. Format = true;
  1074. }
  1075. else
  1076. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  1077. if (S.GetFormatNSStringIdx(I, Idx)) {
  1078. Format = true;
  1079. break;
  1080. }
  1081. }
  1082. if (!Format || NumArgs <= Idx)
  1083. return;
  1084. const Expr *FormatExpr = Args[Idx];
  1085. if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
  1086. FormatExpr = CSCE->getSubExpr();
  1087. const StringLiteral *FormatString;
  1088. if (const ObjCStringLiteral *OSL =
  1089. dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
  1090. FormatString = OSL->getString();
  1091. else
  1092. FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
  1093. if (!FormatString)
  1094. return;
  1095. if (S.FormatStringHasSArg(FormatString)) {
  1096. S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
  1097. << "%s" << 1 << 1;
  1098. S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
  1099. << FDecl->getDeclName();
  1100. }
  1101. }
  1102. #endif // HLSL Change Ends
  1103. /// Determine whether the given type has a non-null nullability annotation.
  1104. static bool isNonNullType(ASTContext &ctx, QualType type) {
  1105. if (auto nullability = type->getNullability(ctx))
  1106. return *nullability == NullabilityKind::NonNull;
  1107. return false;
  1108. }
  1109. static void CheckNonNullArguments(Sema &S,
  1110. const NamedDecl *FDecl,
  1111. const FunctionProtoType *Proto,
  1112. ArrayRef<const Expr *> Args,
  1113. SourceLocation CallSiteLoc) {
  1114. assert((FDecl || Proto) && "Need a function declaration or prototype");
  1115. // Check the attributes attached to the method/function itself.
  1116. llvm::SmallBitVector NonNullArgs;
  1117. if (FDecl) {
  1118. // Handle the nonnull attribute on the function/method declaration itself.
  1119. for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
  1120. if (!NonNull->args_size()) {
  1121. // Easy case: all pointer arguments are nonnull.
  1122. for (const auto *Arg : Args)
  1123. if (S.isValidPointerAttrType(Arg->getType()))
  1124. CheckNonNullArgument(S, Arg, CallSiteLoc);
  1125. return;
  1126. }
  1127. for (unsigned Val : NonNull->args()) {
  1128. if (Val >= Args.size())
  1129. continue;
  1130. if (NonNullArgs.empty())
  1131. NonNullArgs.resize(Args.size());
  1132. NonNullArgs.set(Val);
  1133. }
  1134. }
  1135. }
  1136. if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
  1137. // Handle the nonnull attribute on the parameters of the
  1138. // function/method.
  1139. ArrayRef<ParmVarDecl*> parms;
  1140. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
  1141. parms = FD->parameters();
  1142. else
  1143. parms = cast<ObjCMethodDecl>(FDecl)->parameters();
  1144. unsigned ParamIndex = 0;
  1145. for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
  1146. I != E; ++I, ++ParamIndex) {
  1147. const ParmVarDecl *PVD = *I;
  1148. if (PVD->hasAttr<NonNullAttr>() ||
  1149. isNonNullType(S.Context, PVD->getType())) {
  1150. if (NonNullArgs.empty())
  1151. NonNullArgs.resize(Args.size());
  1152. NonNullArgs.set(ParamIndex);
  1153. }
  1154. }
  1155. } else {
  1156. // If we have a non-function, non-method declaration but no
  1157. // function prototype, try to dig out the function prototype.
  1158. if (!Proto) {
  1159. if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
  1160. QualType type = VD->getType().getNonReferenceType();
  1161. if (auto pointerType = type->getAs<PointerType>())
  1162. type = pointerType->getPointeeType();
  1163. else if (auto blockType = type->getAs<BlockPointerType>())
  1164. type = blockType->getPointeeType();
  1165. // FIXME: data member pointers?
  1166. // Dig out the function prototype, if there is one.
  1167. Proto = type->getAs<FunctionProtoType>();
  1168. }
  1169. }
  1170. // Fill in non-null argument information from the nullability
  1171. // information on the parameter types (if we have them).
  1172. if (Proto) {
  1173. unsigned Index = 0;
  1174. for (auto paramType : Proto->getParamTypes()) {
  1175. if (isNonNullType(S.Context, paramType)) {
  1176. if (NonNullArgs.empty())
  1177. NonNullArgs.resize(Args.size());
  1178. NonNullArgs.set(Index);
  1179. }
  1180. ++Index;
  1181. }
  1182. }
  1183. }
  1184. // Check for non-null arguments.
  1185. for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
  1186. ArgIndex != ArgIndexEnd; ++ArgIndex) {
  1187. if (NonNullArgs[ArgIndex])
  1188. CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
  1189. }
  1190. }
  1191. /// Handles the checks for format strings, non-POD arguments to vararg
  1192. /// functions, and NULL arguments passed to non-NULL parameters.
  1193. void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
  1194. ArrayRef<const Expr *> Args, bool IsMemberFunction,
  1195. SourceLocation Loc, SourceRange Range,
  1196. VariadicCallType CallType) {
  1197. // FIXME: We should check as much as we can in the template definition.
  1198. if (CurContext->isDependentContext())
  1199. return;
  1200. #if 1 // HLSL Change - no format string support
  1201. (void)(IsMemberFunction); (void)(CallType); (void)(Range);
  1202. #else
  1203. // Printf and scanf checking.
  1204. llvm::SmallBitVector CheckedVarArgs;
  1205. if (FDecl) {
  1206. for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
  1207. // Only create vector if there are format attributes.
  1208. CheckedVarArgs.resize(Args.size());
  1209. CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
  1210. CheckedVarArgs);
  1211. }
  1212. }
  1213. // Refuse POD arguments that weren't caught by the format string
  1214. // checks above.
  1215. if (CallType != VariadicDoesNotApply) {
  1216. unsigned NumParams = Proto ? Proto->getNumParams()
  1217. : FDecl && isa<FunctionDecl>(FDecl)
  1218. ? cast<FunctionDecl>(FDecl)->getNumParams()
  1219. : FDecl && isa<ObjCMethodDecl>(FDecl)
  1220. ? cast<ObjCMethodDecl>(FDecl)->param_size()
  1221. : 0;
  1222. for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
  1223. // Args[ArgIdx] can be null in malformed code.
  1224. if (const Expr *Arg = Args[ArgIdx]) {
  1225. if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
  1226. checkVariadicArgument(Arg, CallType);
  1227. }
  1228. }
  1229. }
  1230. #endif // HLSL Change - no format string support
  1231. if (FDecl || Proto) {
  1232. CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
  1233. // Type safety checking.
  1234. if (FDecl) {
  1235. for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
  1236. CheckArgumentWithTypeTag(I, Args.data());
  1237. }
  1238. }
  1239. }
  1240. /// CheckConstructorCall - Check a constructor call for correctness and safety
  1241. /// properties not enforced by the C type system.
  1242. void Sema::CheckConstructorCall(FunctionDecl *FDecl,
  1243. ArrayRef<const Expr *> Args,
  1244. const FunctionProtoType *Proto,
  1245. SourceLocation Loc) {
  1246. VariadicCallType CallType =
  1247. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  1248. checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
  1249. CallType);
  1250. }
  1251. /// CheckFunctionCall - Check a direct function call for various correctness
  1252. /// and safety properties not strictly enforced by the C type system.
  1253. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  1254. const FunctionProtoType *Proto) {
  1255. bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
  1256. isa<CXXMethodDecl>(FDecl);
  1257. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
  1258. IsMemberOperatorCall;
  1259. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  1260. TheCall->getCallee());
  1261. Expr** Args = TheCall->getArgs();
  1262. unsigned NumArgs = TheCall->getNumArgs();
  1263. if (IsMemberOperatorCall) {
  1264. // If this is a call to a member operator, hide the first argument
  1265. // from checkCall.
  1266. // FIXME: Our choice of AST representation here is less than ideal.
  1267. ++Args;
  1268. --NumArgs;
  1269. }
  1270. checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
  1271. IsMemberFunction, TheCall->getRParenLoc(),
  1272. TheCall->getCallee()->getSourceRange(), CallType);
  1273. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  1274. // None of the checks below are needed for functions that don't have
  1275. // simple names (e.g., C++ conversion functions).
  1276. if (!FnInfo)
  1277. return false;
  1278. CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
  1279. #if 0 // HLSL Change Starts
  1280. if (getLangOpts().ObjC1)
  1281. DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
  1282. unsigned CMId = FDecl->getMemoryFunctionKind();
  1283. if (CMId == 0)
  1284. return false;
  1285. // Handle memory setting and copying functions.
  1286. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  1287. CheckStrlcpycatArguments(TheCall, FnInfo);
  1288. else if (CMId == Builtin::BIstrncat)
  1289. CheckStrncatArguments(TheCall, FnInfo);
  1290. else
  1291. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  1292. #endif // HLSL Change Ends
  1293. return false;
  1294. }
  1295. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  1296. ArrayRef<const Expr *> Args) {
  1297. #if 0 // HLSL Change Starts
  1298. VariadicCallType CallType =
  1299. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  1300. checkCall(Method, nullptr, Args,
  1301. /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
  1302. CallType);
  1303. #endif // HLSL Change Ends
  1304. return false;
  1305. }
  1306. bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
  1307. const FunctionProtoType *Proto) {
  1308. #if 0 // HLSL Change Starts
  1309. QualType Ty;
  1310. if (const auto *V = dyn_cast<VarDecl>(NDecl))
  1311. Ty = V->getType().getNonReferenceType();
  1312. else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
  1313. Ty = F->getType().getNonReferenceType();
  1314. else
  1315. return false;
  1316. if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
  1317. !Ty->isFunctionProtoType())
  1318. return false;
  1319. VariadicCallType CallType;
  1320. if (!Proto || !Proto->isVariadic()) {
  1321. CallType = VariadicDoesNotApply;
  1322. } else if (Ty->isBlockPointerType()) {
  1323. CallType = VariadicBlock;
  1324. } else { // Ty->isFunctionPointerType()
  1325. CallType = VariadicFunction;
  1326. }
  1327. checkCall(NDecl, Proto,
  1328. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  1329. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  1330. TheCall->getCallee()->getSourceRange(), CallType);
  1331. #endif // HLSL Change Ends
  1332. return false;
  1333. }
  1334. /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
  1335. /// such as function pointers returned from functions.
  1336. bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
  1337. VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
  1338. TheCall->getCallee());
  1339. checkCall(/*FDecl=*/nullptr, Proto,
  1340. llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
  1341. /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
  1342. TheCall->getCallee()->getSourceRange(), CallType);
  1343. return false;
  1344. }
  1345. static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
  1346. if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
  1347. Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
  1348. return false;
  1349. switch (Op) {
  1350. case AtomicExpr::AO__c11_atomic_init:
  1351. llvm_unreachable("There is no ordering argument for an init");
  1352. case AtomicExpr::AO__c11_atomic_load:
  1353. case AtomicExpr::AO__atomic_load_n:
  1354. case AtomicExpr::AO__atomic_load:
  1355. return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
  1356. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  1357. case AtomicExpr::AO__c11_atomic_store:
  1358. case AtomicExpr::AO__atomic_store:
  1359. case AtomicExpr::AO__atomic_store_n:
  1360. return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
  1361. Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
  1362. Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
  1363. default:
  1364. return true;
  1365. }
  1366. }
  1367. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  1368. AtomicExpr::AtomicOp Op) {
  1369. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  1370. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1371. // All these operations take one of the following forms:
  1372. enum {
  1373. // C __c11_atomic_init(A *, C)
  1374. Init,
  1375. // C __c11_atomic_load(A *, int)
  1376. Load,
  1377. // void __atomic_load(A *, CP, int)
  1378. Copy,
  1379. // C __c11_atomic_add(A *, M, int)
  1380. Arithmetic,
  1381. // C __atomic_exchange_n(A *, CP, int)
  1382. Xchg,
  1383. // void __atomic_exchange(A *, C *, CP, int)
  1384. GNUXchg,
  1385. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  1386. C11CmpXchg,
  1387. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  1388. GNUCmpXchg
  1389. } Form = Init;
  1390. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  1391. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  1392. // where:
  1393. // C is an appropriate type,
  1394. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  1395. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  1396. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  1397. // the int parameters are for orderings.
  1398. static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  1399. AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
  1400. AtomicExpr::AO__atomic_load,
  1401. "need to update code for modified C11 atomics");
  1402. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  1403. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  1404. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  1405. Op == AtomicExpr::AO__atomic_store_n ||
  1406. Op == AtomicExpr::AO__atomic_exchange_n ||
  1407. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  1408. bool IsAddSub = false;
  1409. switch (Op) {
  1410. case AtomicExpr::AO__c11_atomic_init:
  1411. Form = Init;
  1412. break;
  1413. case AtomicExpr::AO__c11_atomic_load:
  1414. case AtomicExpr::AO__atomic_load_n:
  1415. Form = Load;
  1416. break;
  1417. case AtomicExpr::AO__c11_atomic_store:
  1418. case AtomicExpr::AO__atomic_load:
  1419. case AtomicExpr::AO__atomic_store:
  1420. case AtomicExpr::AO__atomic_store_n:
  1421. Form = Copy;
  1422. break;
  1423. case AtomicExpr::AO__c11_atomic_fetch_add:
  1424. case AtomicExpr::AO__c11_atomic_fetch_sub:
  1425. case AtomicExpr::AO__atomic_fetch_add:
  1426. case AtomicExpr::AO__atomic_fetch_sub:
  1427. case AtomicExpr::AO__atomic_add_fetch:
  1428. case AtomicExpr::AO__atomic_sub_fetch:
  1429. IsAddSub = true;
  1430. // Fall through.
  1431. case AtomicExpr::AO__c11_atomic_fetch_and:
  1432. case AtomicExpr::AO__c11_atomic_fetch_or:
  1433. case AtomicExpr::AO__c11_atomic_fetch_xor:
  1434. case AtomicExpr::AO__atomic_fetch_and:
  1435. case AtomicExpr::AO__atomic_fetch_or:
  1436. case AtomicExpr::AO__atomic_fetch_xor:
  1437. case AtomicExpr::AO__atomic_fetch_nand:
  1438. case AtomicExpr::AO__atomic_and_fetch:
  1439. case AtomicExpr::AO__atomic_or_fetch:
  1440. case AtomicExpr::AO__atomic_xor_fetch:
  1441. case AtomicExpr::AO__atomic_nand_fetch:
  1442. Form = Arithmetic;
  1443. break;
  1444. case AtomicExpr::AO__c11_atomic_exchange:
  1445. case AtomicExpr::AO__atomic_exchange_n:
  1446. Form = Xchg;
  1447. break;
  1448. case AtomicExpr::AO__atomic_exchange:
  1449. Form = GNUXchg;
  1450. break;
  1451. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  1452. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  1453. Form = C11CmpXchg;
  1454. break;
  1455. case AtomicExpr::AO__atomic_compare_exchange:
  1456. case AtomicExpr::AO__atomic_compare_exchange_n:
  1457. Form = GNUCmpXchg;
  1458. break;
  1459. }
  1460. // Check we have the right number of arguments.
  1461. if (TheCall->getNumArgs() < NumArgs[Form]) {
  1462. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1463. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  1464. << TheCall->getCallee()->getSourceRange();
  1465. return ExprError();
  1466. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  1467. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  1468. diag::err_typecheck_call_too_many_args)
  1469. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  1470. << TheCall->getCallee()->getSourceRange();
  1471. return ExprError();
  1472. }
  1473. // Inspect the first argument of the atomic operation.
  1474. Expr *Ptr = TheCall->getArg(0);
  1475. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  1476. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  1477. if (!pointerType) {
  1478. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1479. << Ptr->getType() << Ptr->getSourceRange();
  1480. return ExprError();
  1481. }
  1482. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  1483. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  1484. QualType ValType = AtomTy; // 'C'
  1485. if (IsC11) {
  1486. if (!AtomTy->isAtomicType()) {
  1487. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  1488. << Ptr->getType() << Ptr->getSourceRange();
  1489. return ExprError();
  1490. }
  1491. if (AtomTy.isConstQualified()) {
  1492. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
  1493. << Ptr->getType() << Ptr->getSourceRange();
  1494. return ExprError();
  1495. }
  1496. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  1497. }
  1498. // For an arithmetic operation, the implied arithmetic must be well-formed.
  1499. if (Form == Arithmetic) {
  1500. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  1501. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  1502. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  1503. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1504. return ExprError();
  1505. }
  1506. if (!IsAddSub && !ValType->isIntegerType()) {
  1507. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  1508. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1509. return ExprError();
  1510. }
  1511. if (IsC11 && ValType->isPointerType() &&
  1512. RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
  1513. diag::err_incomplete_type)) {
  1514. return ExprError();
  1515. }
  1516. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  1517. // For __atomic_*_n operations, the value type must be a scalar integral or
  1518. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  1519. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  1520. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  1521. return ExprError();
  1522. }
  1523. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
  1524. !AtomTy->isScalarType()) {
  1525. // For GNU atomics, require a trivially-copyable type. This is not part of
  1526. // the GNU atomics specification, but we enforce it for sanity.
  1527. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  1528. << Ptr->getType() << Ptr->getSourceRange();
  1529. return ExprError();
  1530. }
  1531. // FIXME: For any builtin other than a load, the ValType must not be
  1532. // const-qualified.
  1533. switch (ValType.getObjCLifetime()) {
  1534. case Qualifiers::OCL_None:
  1535. case Qualifiers::OCL_ExplicitNone:
  1536. // okay
  1537. break;
  1538. case Qualifiers::OCL_Weak:
  1539. case Qualifiers::OCL_Strong:
  1540. case Qualifiers::OCL_Autoreleasing:
  1541. // FIXME: Can this happen? By this point, ValType should be known
  1542. // to be trivially copyable.
  1543. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1544. << ValType << Ptr->getSourceRange();
  1545. return ExprError();
  1546. }
  1547. // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
  1548. // volatile-ness of the pointee-type inject itself into the result or the
  1549. // other operands.
  1550. ValType.removeLocalVolatile();
  1551. QualType ResultType = ValType;
  1552. if (Form == Copy || Form == GNUXchg || Form == Init)
  1553. ResultType = Context.VoidTy;
  1554. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  1555. ResultType = Context.BoolTy;
  1556. // The type of a parameter passed 'by value'. In the GNU atomics, such
  1557. // arguments are actually passed as pointers.
  1558. QualType ByValType = ValType; // 'CP'
  1559. if (!IsC11 && !IsN)
  1560. ByValType = Ptr->getType();
  1561. // The first argument --- the pointer --- has a fixed type; we
  1562. // deduce the types of the rest of the arguments accordingly. Walk
  1563. // the remaining arguments, converting them to the deduced value type.
  1564. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  1565. QualType Ty;
  1566. if (i < NumVals[Form] + 1) {
  1567. switch (i) {
  1568. case 1:
  1569. // The second argument is the non-atomic operand. For arithmetic, this
  1570. // is always passed by value, and for a compare_exchange it is always
  1571. // passed by address. For the rest, GNU uses by-address and C11 uses
  1572. // by-value.
  1573. assert(Form != Load);
  1574. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  1575. Ty = ValType;
  1576. else if (Form == Copy || Form == Xchg)
  1577. Ty = ByValType;
  1578. else if (Form == Arithmetic)
  1579. Ty = Context.getPointerDiffType();
  1580. else
  1581. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  1582. break;
  1583. case 2:
  1584. // The third argument to compare_exchange / GNU exchange is a
  1585. // (pointer to a) desired value.
  1586. Ty = ByValType;
  1587. break;
  1588. case 3:
  1589. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  1590. Ty = Context.BoolTy;
  1591. break;
  1592. }
  1593. } else {
  1594. // The order(s) are always converted to int.
  1595. Ty = Context.IntTy;
  1596. }
  1597. InitializedEntity Entity =
  1598. InitializedEntity::InitializeParameter(Context, Ty, false);
  1599. ExprResult Arg = TheCall->getArg(i);
  1600. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1601. if (Arg.isInvalid())
  1602. return true;
  1603. TheCall->setArg(i, Arg.get());
  1604. }
  1605. // Permute the arguments into a 'consistent' order.
  1606. SmallVector<Expr*, 5> SubExprs;
  1607. SubExprs.push_back(Ptr);
  1608. switch (Form) {
  1609. case Init:
  1610. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  1611. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1612. break;
  1613. case Load:
  1614. SubExprs.push_back(TheCall->getArg(1)); // Order
  1615. break;
  1616. case Copy:
  1617. case Arithmetic:
  1618. case Xchg:
  1619. SubExprs.push_back(TheCall->getArg(2)); // Order
  1620. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1621. break;
  1622. case GNUXchg:
  1623. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  1624. SubExprs.push_back(TheCall->getArg(3)); // Order
  1625. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1626. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1627. break;
  1628. case C11CmpXchg:
  1629. SubExprs.push_back(TheCall->getArg(3)); // Order
  1630. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1631. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  1632. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1633. break;
  1634. case GNUCmpXchg:
  1635. SubExprs.push_back(TheCall->getArg(4)); // Order
  1636. SubExprs.push_back(TheCall->getArg(1)); // Val1
  1637. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  1638. SubExprs.push_back(TheCall->getArg(2)); // Val2
  1639. SubExprs.push_back(TheCall->getArg(3)); // Weak
  1640. break;
  1641. }
  1642. if (SubExprs.size() >= 2 && Form != Init) {
  1643. llvm::APSInt Result(32);
  1644. if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
  1645. !isValidOrderingForOp(Result.getSExtValue(), Op))
  1646. Diag(SubExprs[1]->getLocStart(),
  1647. diag::warn_atomic_op_has_invalid_memory_order)
  1648. << SubExprs[1]->getSourceRange();
  1649. }
  1650. AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  1651. SubExprs, ResultType, Op,
  1652. TheCall->getRParenLoc());
  1653. if ((Op == AtomicExpr::AO__c11_atomic_load ||
  1654. (Op == AtomicExpr::AO__c11_atomic_store)) &&
  1655. Context.AtomicUsesUnsupportedLibcall(AE))
  1656. Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
  1657. ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
  1658. return AE;
  1659. }
  1660. /// checkBuiltinArgument - Given a call to a builtin function, perform
  1661. /// normal type-checking on the given argument, updating the call in
  1662. /// place. This is useful when a builtin function requires custom
  1663. /// type-checking for some of its arguments but not necessarily all of
  1664. /// them.
  1665. ///
  1666. /// Returns true on error.
  1667. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  1668. FunctionDecl *Fn = E->getDirectCallee();
  1669. assert(Fn && "builtin call without direct callee!");
  1670. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  1671. InitializedEntity Entity =
  1672. InitializedEntity::InitializeParameter(S.Context, Param);
  1673. ExprResult Arg = E->getArg(0);
  1674. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1675. if (Arg.isInvalid())
  1676. return true;
  1677. E->setArg(ArgIndex, Arg.get());
  1678. return false;
  1679. }
  1680. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  1681. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  1682. /// type of its first argument. The main ActOnCallExpr routines have already
  1683. /// promoted the types of arguments because all of these calls are prototyped as
  1684. /// void(...).
  1685. ///
  1686. /// This function goes through and does final semantic checking for these
  1687. /// builtins,
  1688. ExprResult
  1689. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  1690. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  1691. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1692. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1693. // Ensure that we have at least one argument to do type inference from.
  1694. if (TheCall->getNumArgs() < 1) {
  1695. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1696. << 0 << 1 << TheCall->getNumArgs()
  1697. << TheCall->getCallee()->getSourceRange();
  1698. return ExprError();
  1699. }
  1700. // Inspect the first argument of the atomic builtin. This should always be
  1701. // a pointer type, whose element is an integral scalar or pointer type.
  1702. // Because it is a pointer type, we don't have to worry about any implicit
  1703. // casts here.
  1704. // FIXME: We don't allow floating point scalars as input.
  1705. Expr *FirstArg = TheCall->getArg(0);
  1706. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  1707. if (FirstArgResult.isInvalid())
  1708. return ExprError();
  1709. FirstArg = FirstArgResult.get();
  1710. TheCall->setArg(0, FirstArg);
  1711. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  1712. if (!pointerType) {
  1713. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  1714. << FirstArg->getType() << FirstArg->getSourceRange();
  1715. return ExprError();
  1716. }
  1717. QualType ValType = pointerType->getPointeeType();
  1718. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  1719. !ValType->isBlockPointerType()) {
  1720. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  1721. << FirstArg->getType() << FirstArg->getSourceRange();
  1722. return ExprError();
  1723. }
  1724. switch (ValType.getObjCLifetime()) {
  1725. case Qualifiers::OCL_None:
  1726. case Qualifiers::OCL_ExplicitNone:
  1727. // okay
  1728. break;
  1729. case Qualifiers::OCL_Weak:
  1730. case Qualifiers::OCL_Strong:
  1731. case Qualifiers::OCL_Autoreleasing:
  1732. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  1733. << ValType << FirstArg->getSourceRange();
  1734. return ExprError();
  1735. }
  1736. // Strip any qualifiers off ValType.
  1737. ValType = ValType.getUnqualifiedType();
  1738. // The majority of builtins return a value, but a few have special return
  1739. // types, so allow them to override appropriately below.
  1740. QualType ResultType = ValType;
  1741. // We need to figure out which concrete builtin this maps onto. For example,
  1742. // __sync_fetch_and_add with a 2 byte object turns into
  1743. // __sync_fetch_and_add_2.
  1744. #define BUILTIN_ROW(x) \
  1745. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  1746. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  1747. static const unsigned BuiltinIndices[][5] = {
  1748. BUILTIN_ROW(__sync_fetch_and_add),
  1749. BUILTIN_ROW(__sync_fetch_and_sub),
  1750. BUILTIN_ROW(__sync_fetch_and_or),
  1751. BUILTIN_ROW(__sync_fetch_and_and),
  1752. BUILTIN_ROW(__sync_fetch_and_xor),
  1753. BUILTIN_ROW(__sync_fetch_and_nand),
  1754. BUILTIN_ROW(__sync_add_and_fetch),
  1755. BUILTIN_ROW(__sync_sub_and_fetch),
  1756. BUILTIN_ROW(__sync_and_and_fetch),
  1757. BUILTIN_ROW(__sync_or_and_fetch),
  1758. BUILTIN_ROW(__sync_xor_and_fetch),
  1759. BUILTIN_ROW(__sync_nand_and_fetch),
  1760. BUILTIN_ROW(__sync_val_compare_and_swap),
  1761. BUILTIN_ROW(__sync_bool_compare_and_swap),
  1762. BUILTIN_ROW(__sync_lock_test_and_set),
  1763. BUILTIN_ROW(__sync_lock_release),
  1764. BUILTIN_ROW(__sync_swap)
  1765. };
  1766. #undef BUILTIN_ROW
  1767. // Determine the index of the size.
  1768. unsigned SizeIndex;
  1769. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  1770. case 1: SizeIndex = 0; break;
  1771. case 2: SizeIndex = 1; break;
  1772. case 4: SizeIndex = 2; break;
  1773. case 8: SizeIndex = 3; break;
  1774. case 16: SizeIndex = 4; break;
  1775. default:
  1776. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  1777. << FirstArg->getType() << FirstArg->getSourceRange();
  1778. return ExprError();
  1779. }
  1780. // Each of these builtins has one pointer argument, followed by some number of
  1781. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  1782. // that we ignore. Find out which row of BuiltinIndices to read from as well
  1783. // as the number of fixed args.
  1784. unsigned BuiltinID = FDecl->getBuiltinID();
  1785. unsigned BuiltinIndex, NumFixed = 1;
  1786. bool WarnAboutSemanticsChange = false;
  1787. switch (BuiltinID) {
  1788. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  1789. case Builtin::BI__sync_fetch_and_add:
  1790. case Builtin::BI__sync_fetch_and_add_1:
  1791. case Builtin::BI__sync_fetch_and_add_2:
  1792. case Builtin::BI__sync_fetch_and_add_4:
  1793. case Builtin::BI__sync_fetch_and_add_8:
  1794. case Builtin::BI__sync_fetch_and_add_16:
  1795. BuiltinIndex = 0;
  1796. break;
  1797. case Builtin::BI__sync_fetch_and_sub:
  1798. case Builtin::BI__sync_fetch_and_sub_1:
  1799. case Builtin::BI__sync_fetch_and_sub_2:
  1800. case Builtin::BI__sync_fetch_and_sub_4:
  1801. case Builtin::BI__sync_fetch_and_sub_8:
  1802. case Builtin::BI__sync_fetch_and_sub_16:
  1803. BuiltinIndex = 1;
  1804. break;
  1805. case Builtin::BI__sync_fetch_and_or:
  1806. case Builtin::BI__sync_fetch_and_or_1:
  1807. case Builtin::BI__sync_fetch_and_or_2:
  1808. case Builtin::BI__sync_fetch_and_or_4:
  1809. case Builtin::BI__sync_fetch_and_or_8:
  1810. case Builtin::BI__sync_fetch_and_or_16:
  1811. BuiltinIndex = 2;
  1812. break;
  1813. case Builtin::BI__sync_fetch_and_and:
  1814. case Builtin::BI__sync_fetch_and_and_1:
  1815. case Builtin::BI__sync_fetch_and_and_2:
  1816. case Builtin::BI__sync_fetch_and_and_4:
  1817. case Builtin::BI__sync_fetch_and_and_8:
  1818. case Builtin::BI__sync_fetch_and_and_16:
  1819. BuiltinIndex = 3;
  1820. break;
  1821. case Builtin::BI__sync_fetch_and_xor:
  1822. case Builtin::BI__sync_fetch_and_xor_1:
  1823. case Builtin::BI__sync_fetch_and_xor_2:
  1824. case Builtin::BI__sync_fetch_and_xor_4:
  1825. case Builtin::BI__sync_fetch_and_xor_8:
  1826. case Builtin::BI__sync_fetch_and_xor_16:
  1827. BuiltinIndex = 4;
  1828. break;
  1829. case Builtin::BI__sync_fetch_and_nand:
  1830. case Builtin::BI__sync_fetch_and_nand_1:
  1831. case Builtin::BI__sync_fetch_and_nand_2:
  1832. case Builtin::BI__sync_fetch_and_nand_4:
  1833. case Builtin::BI__sync_fetch_and_nand_8:
  1834. case Builtin::BI__sync_fetch_and_nand_16:
  1835. BuiltinIndex = 5;
  1836. WarnAboutSemanticsChange = true;
  1837. break;
  1838. case Builtin::BI__sync_add_and_fetch:
  1839. case Builtin::BI__sync_add_and_fetch_1:
  1840. case Builtin::BI__sync_add_and_fetch_2:
  1841. case Builtin::BI__sync_add_and_fetch_4:
  1842. case Builtin::BI__sync_add_and_fetch_8:
  1843. case Builtin::BI__sync_add_and_fetch_16:
  1844. BuiltinIndex = 6;
  1845. break;
  1846. case Builtin::BI__sync_sub_and_fetch:
  1847. case Builtin::BI__sync_sub_and_fetch_1:
  1848. case Builtin::BI__sync_sub_and_fetch_2:
  1849. case Builtin::BI__sync_sub_and_fetch_4:
  1850. case Builtin::BI__sync_sub_and_fetch_8:
  1851. case Builtin::BI__sync_sub_and_fetch_16:
  1852. BuiltinIndex = 7;
  1853. break;
  1854. case Builtin::BI__sync_and_and_fetch:
  1855. case Builtin::BI__sync_and_and_fetch_1:
  1856. case Builtin::BI__sync_and_and_fetch_2:
  1857. case Builtin::BI__sync_and_and_fetch_4:
  1858. case Builtin::BI__sync_and_and_fetch_8:
  1859. case Builtin::BI__sync_and_and_fetch_16:
  1860. BuiltinIndex = 8;
  1861. break;
  1862. case Builtin::BI__sync_or_and_fetch:
  1863. case Builtin::BI__sync_or_and_fetch_1:
  1864. case Builtin::BI__sync_or_and_fetch_2:
  1865. case Builtin::BI__sync_or_and_fetch_4:
  1866. case Builtin::BI__sync_or_and_fetch_8:
  1867. case Builtin::BI__sync_or_and_fetch_16:
  1868. BuiltinIndex = 9;
  1869. break;
  1870. case Builtin::BI__sync_xor_and_fetch:
  1871. case Builtin::BI__sync_xor_and_fetch_1:
  1872. case Builtin::BI__sync_xor_and_fetch_2:
  1873. case Builtin::BI__sync_xor_and_fetch_4:
  1874. case Builtin::BI__sync_xor_and_fetch_8:
  1875. case Builtin::BI__sync_xor_and_fetch_16:
  1876. BuiltinIndex = 10;
  1877. break;
  1878. case Builtin::BI__sync_nand_and_fetch:
  1879. case Builtin::BI__sync_nand_and_fetch_1:
  1880. case Builtin::BI__sync_nand_and_fetch_2:
  1881. case Builtin::BI__sync_nand_and_fetch_4:
  1882. case Builtin::BI__sync_nand_and_fetch_8:
  1883. case Builtin::BI__sync_nand_and_fetch_16:
  1884. BuiltinIndex = 11;
  1885. WarnAboutSemanticsChange = true;
  1886. break;
  1887. case Builtin::BI__sync_val_compare_and_swap:
  1888. case Builtin::BI__sync_val_compare_and_swap_1:
  1889. case Builtin::BI__sync_val_compare_and_swap_2:
  1890. case Builtin::BI__sync_val_compare_and_swap_4:
  1891. case Builtin::BI__sync_val_compare_and_swap_8:
  1892. case Builtin::BI__sync_val_compare_and_swap_16:
  1893. BuiltinIndex = 12;
  1894. NumFixed = 2;
  1895. break;
  1896. case Builtin::BI__sync_bool_compare_and_swap:
  1897. case Builtin::BI__sync_bool_compare_and_swap_1:
  1898. case Builtin::BI__sync_bool_compare_and_swap_2:
  1899. case Builtin::BI__sync_bool_compare_and_swap_4:
  1900. case Builtin::BI__sync_bool_compare_and_swap_8:
  1901. case Builtin::BI__sync_bool_compare_and_swap_16:
  1902. BuiltinIndex = 13;
  1903. NumFixed = 2;
  1904. ResultType = Context.BoolTy;
  1905. break;
  1906. case Builtin::BI__sync_lock_test_and_set:
  1907. case Builtin::BI__sync_lock_test_and_set_1:
  1908. case Builtin::BI__sync_lock_test_and_set_2:
  1909. case Builtin::BI__sync_lock_test_and_set_4:
  1910. case Builtin::BI__sync_lock_test_and_set_8:
  1911. case Builtin::BI__sync_lock_test_and_set_16:
  1912. BuiltinIndex = 14;
  1913. break;
  1914. case Builtin::BI__sync_lock_release:
  1915. case Builtin::BI__sync_lock_release_1:
  1916. case Builtin::BI__sync_lock_release_2:
  1917. case Builtin::BI__sync_lock_release_4:
  1918. case Builtin::BI__sync_lock_release_8:
  1919. case Builtin::BI__sync_lock_release_16:
  1920. BuiltinIndex = 15;
  1921. NumFixed = 0;
  1922. ResultType = Context.VoidTy;
  1923. break;
  1924. case Builtin::BI__sync_swap:
  1925. case Builtin::BI__sync_swap_1:
  1926. case Builtin::BI__sync_swap_2:
  1927. case Builtin::BI__sync_swap_4:
  1928. case Builtin::BI__sync_swap_8:
  1929. case Builtin::BI__sync_swap_16:
  1930. BuiltinIndex = 16;
  1931. break;
  1932. }
  1933. // Now that we know how many fixed arguments we expect, first check that we
  1934. // have at least that many.
  1935. if (TheCall->getNumArgs() < 1+NumFixed) {
  1936. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1937. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1938. << TheCall->getCallee()->getSourceRange();
  1939. return ExprError();
  1940. }
  1941. if (WarnAboutSemanticsChange) {
  1942. Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
  1943. << TheCall->getCallee()->getSourceRange();
  1944. }
  1945. // Get the decl for the concrete builtin from this, we can tell what the
  1946. // concrete integer type we should convert to is.
  1947. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1948. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  1949. FunctionDecl *NewBuiltinDecl;
  1950. if (NewBuiltinID == BuiltinID)
  1951. NewBuiltinDecl = FDecl;
  1952. else {
  1953. // Perform builtin lookup to avoid redeclaring it.
  1954. DeclarationName DN(&Context.Idents.get(NewBuiltinName));
  1955. LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
  1956. LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
  1957. assert(Res.getFoundDecl());
  1958. NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
  1959. if (!NewBuiltinDecl)
  1960. return ExprError();
  1961. }
  1962. // The first argument --- the pointer --- has a fixed type; we
  1963. // deduce the types of the rest of the arguments accordingly. Walk
  1964. // the remaining arguments, converting them to the deduced value type.
  1965. for (unsigned i = 0; i != NumFixed; ++i) {
  1966. ExprResult Arg = TheCall->getArg(i+1);
  1967. // GCC does an implicit conversion to the pointer or integer ValType. This
  1968. // can fail in some cases (1i -> int**), check for this error case now.
  1969. // Initialize the argument.
  1970. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1971. ValType, /*consume*/ false);
  1972. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1973. if (Arg.isInvalid())
  1974. return ExprError();
  1975. // Okay, we have something that *can* be converted to the right type. Check
  1976. // to see if there is a potentially weird extension going on here. This can
  1977. // happen when you do an atomic operation on something like an char* and
  1978. // pass in 42. The 42 gets converted to char. This is even more strange
  1979. // for things like 45.123 -> char, etc.
  1980. // FIXME: Do this check.
  1981. TheCall->setArg(i+1, Arg.get());
  1982. }
  1983. ASTContext& Context = this->getASTContext();
  1984. // Create a new DeclRefExpr to refer to the new decl.
  1985. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1986. Context,
  1987. DRE->getQualifierLoc(),
  1988. SourceLocation(),
  1989. NewBuiltinDecl,
  1990. /*enclosing*/ false,
  1991. DRE->getLocation(),
  1992. Context.BuiltinFnTy,
  1993. DRE->getValueKind());
  1994. // Set the callee in the CallExpr.
  1995. // FIXME: This loses syntactic information.
  1996. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  1997. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  1998. CK_BuiltinFnToFnPtr);
  1999. TheCall->setCallee(PromotedCall.get());
  2000. // Change the result type of the call to match the original value type. This
  2001. // is arbitrary, but the codegen for these builtins ins design to handle it
  2002. // gracefully.
  2003. TheCall->setType(ResultType);
  2004. return TheCallResult;
  2005. }
  2006. /// CheckObjCString - Checks that the argument to the builtin
  2007. /// CFString constructor is correct
  2008. /// Note: It might also make sense to do the UTF-16 conversion here (would
  2009. /// simplify the backend).
  2010. bool Sema::CheckObjCString(Expr *Arg) {
  2011. #if 0 // HLSL Change Starts
  2012. Arg = Arg->IgnoreParenCasts();
  2013. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  2014. if (!Literal || !Literal->isAscii()) {
  2015. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  2016. << Arg->getSourceRange();
  2017. return true;
  2018. }
  2019. if (Literal->containsNonAsciiOrNull()) {
  2020. StringRef String = Literal->getString();
  2021. unsigned NumBytes = String.size();
  2022. SmallVector<UTF16, 128> ToBuf(NumBytes);
  2023. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2024. UTF16 *ToPtr = &ToBuf[0];
  2025. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2026. &ToPtr, ToPtr + NumBytes,
  2027. strictConversion);
  2028. // Check for conversion failure.
  2029. if (Result != conversionOK)
  2030. Diag(Arg->getLocStart(),
  2031. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  2032. }
  2033. #endif // HLSL Change Ends
  2034. return false;
  2035. }
  2036. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  2037. /// Emit an error and return true on failure, return false on success.
  2038. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  2039. Expr *Fn = TheCall->getCallee();
  2040. if (TheCall->getNumArgs() > 2) {
  2041. Diag(TheCall->getArg(2)->getLocStart(),
  2042. diag::err_typecheck_call_too_many_args)
  2043. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2044. << Fn->getSourceRange()
  2045. << SourceRange(TheCall->getArg(2)->getLocStart(),
  2046. (*(TheCall->arg_end()-1))->getLocEnd());
  2047. return true;
  2048. }
  2049. if (TheCall->getNumArgs() < 2) {
  2050. return Diag(TheCall->getLocEnd(),
  2051. diag::err_typecheck_call_too_few_args_at_least)
  2052. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  2053. }
  2054. // Type-check the first argument normally.
  2055. if (checkBuiltinArgument(*this, TheCall, 0))
  2056. return true;
  2057. // Determine whether the current function is variadic or not.
  2058. BlockScopeInfo *CurBlock = getCurBlock();
  2059. bool isVariadic;
  2060. if (CurBlock)
  2061. isVariadic = CurBlock->TheDecl->isVariadic();
  2062. else if (FunctionDecl *FD = getCurFunctionDecl())
  2063. isVariadic = FD->isVariadic();
  2064. else
  2065. isVariadic = getCurMethodDecl()->isVariadic();
  2066. if (!isVariadic) {
  2067. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  2068. return true;
  2069. }
  2070. // Verify that the second argument to the builtin is the last argument of the
  2071. // current function or method.
  2072. bool SecondArgIsLastNamedArgument = false;
  2073. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  2074. // These are valid if SecondArgIsLastNamedArgument is false after the next
  2075. // block.
  2076. QualType Type;
  2077. SourceLocation ParamLoc;
  2078. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  2079. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  2080. // FIXME: This isn't correct for methods (results in bogus warning).
  2081. // Get the last formal in the current function.
  2082. const ParmVarDecl *LastArg;
  2083. if (CurBlock)
  2084. LastArg = *(CurBlock->TheDecl->param_end()-1);
  2085. else if (FunctionDecl *FD = getCurFunctionDecl())
  2086. LastArg = *(FD->param_end()-1);
  2087. else
  2088. LastArg = *(getCurMethodDecl()->param_end()-1);
  2089. SecondArgIsLastNamedArgument = PV == LastArg;
  2090. Type = PV->getType();
  2091. ParamLoc = PV->getLocation();
  2092. }
  2093. }
  2094. if (!SecondArgIsLastNamedArgument)
  2095. Diag(TheCall->getArg(1)->getLocStart(),
  2096. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  2097. else if (Type->isReferenceType()) {
  2098. Diag(Arg->getLocStart(),
  2099. diag::warn_va_start_of_reference_type_is_undefined);
  2100. Diag(ParamLoc, diag::note_parameter_type) << Type;
  2101. }
  2102. TheCall->setType(Context.VoidTy);
  2103. return false;
  2104. }
  2105. bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
  2106. // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
  2107. // const char *named_addr);
  2108. Expr *Func = Call->getCallee();
  2109. if (Call->getNumArgs() < 3)
  2110. return Diag(Call->getLocEnd(),
  2111. diag::err_typecheck_call_too_few_args_at_least)
  2112. << 0 /*function call*/ << 3 << Call->getNumArgs();
  2113. // Determine whether the current function is variadic or not.
  2114. bool IsVariadic;
  2115. if (BlockScopeInfo *CurBlock = getCurBlock())
  2116. IsVariadic = CurBlock->TheDecl->isVariadic();
  2117. else if (FunctionDecl *FD = getCurFunctionDecl())
  2118. IsVariadic = FD->isVariadic();
  2119. else if (ObjCMethodDecl *MD = getCurMethodDecl())
  2120. IsVariadic = MD->isVariadic();
  2121. else
  2122. llvm_unreachable("unexpected statement type");
  2123. if (!IsVariadic) {
  2124. Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  2125. return true;
  2126. }
  2127. // Type-check the first argument normally.
  2128. if (checkBuiltinArgument(*this, Call, 0))
  2129. return true;
  2130. const struct {
  2131. unsigned ArgNo;
  2132. QualType Type;
  2133. } ArgumentTypes[] = {
  2134. { 1, Context.getPointerType(Context.CharTy.withConst()) },
  2135. { 2, Context.getSizeType() },
  2136. };
  2137. for (const auto &AT : ArgumentTypes) {
  2138. const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
  2139. if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
  2140. continue;
  2141. Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
  2142. << Arg->getType() << AT.Type << 1 /* different class */
  2143. << 0 /* qualifier difference */ << 3 /* parameter mismatch */
  2144. << AT.ArgNo + 1 << Arg->getType() << AT.Type;
  2145. }
  2146. return false;
  2147. }
  2148. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  2149. /// friends. This is declared to take (...), so we have to check everything.
  2150. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  2151. if (TheCall->getNumArgs() < 2)
  2152. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2153. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  2154. if (TheCall->getNumArgs() > 2)
  2155. return Diag(TheCall->getArg(2)->getLocStart(),
  2156. diag::err_typecheck_call_too_many_args)
  2157. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2158. << SourceRange(TheCall->getArg(2)->getLocStart(),
  2159. (*(TheCall->arg_end()-1))->getLocEnd());
  2160. ExprResult OrigArg0 = TheCall->getArg(0);
  2161. ExprResult OrigArg1 = TheCall->getArg(1);
  2162. // Do standard promotions between the two arguments, returning their common
  2163. // type.
  2164. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  2165. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  2166. return true;
  2167. // Make sure any conversions are pushed back into the call; this is
  2168. // type safe since unordered compare builtins are declared as "_Bool
  2169. // foo(...)".
  2170. TheCall->setArg(0, OrigArg0.get());
  2171. TheCall->setArg(1, OrigArg1.get());
  2172. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  2173. return false;
  2174. // If the common type isn't a real floating type, then the arguments were
  2175. // invalid for this operation.
  2176. if (Res.isNull() || !Res->isRealFloatingType())
  2177. return Diag(OrigArg0.get()->getLocStart(),
  2178. diag::err_typecheck_call_invalid_ordered_compare)
  2179. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  2180. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  2181. return false;
  2182. }
  2183. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  2184. /// __builtin_isnan and friends. This is declared to take (...), so we have
  2185. /// to check everything. We expect the last argument to be a floating point
  2186. /// value.
  2187. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  2188. if (TheCall->getNumArgs() < NumArgs)
  2189. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  2190. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  2191. if (TheCall->getNumArgs() > NumArgs)
  2192. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  2193. diag::err_typecheck_call_too_many_args)
  2194. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  2195. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  2196. (*(TheCall->arg_end()-1))->getLocEnd());
  2197. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  2198. if (OrigArg->isTypeDependent())
  2199. return false;
  2200. // This operation requires a non-_Complex floating-point number.
  2201. if (!OrigArg->getType()->isRealFloatingType())
  2202. return Diag(OrigArg->getLocStart(),
  2203. diag::err_typecheck_call_invalid_unary_fp)
  2204. << OrigArg->getType() << OrigArg->getSourceRange();
  2205. // If this is an implicit conversion from float -> double, remove it.
  2206. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  2207. Expr *CastArg = Cast->getSubExpr();
  2208. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  2209. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  2210. "promotion from float to double is the only expected cast here");
  2211. Cast->setSubExpr(nullptr);
  2212. TheCall->setArg(NumArgs-1, CastArg);
  2213. }
  2214. }
  2215. return false;
  2216. }
  2217. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  2218. // This is declared to take (...), so we have to check everything.
  2219. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  2220. if (TheCall->getNumArgs() < 2)
  2221. return ExprError(Diag(TheCall->getLocEnd(),
  2222. diag::err_typecheck_call_too_few_args_at_least)
  2223. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  2224. << TheCall->getSourceRange());
  2225. // Determine which of the following types of shufflevector we're checking:
  2226. // 1) unary, vector mask: (lhs, mask)
  2227. // 2) binary, vector mask: (lhs, rhs, mask)
  2228. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  2229. QualType resType = TheCall->getArg(0)->getType();
  2230. unsigned numElements = 0;
  2231. if (!TheCall->getArg(0)->isTypeDependent() &&
  2232. !TheCall->getArg(1)->isTypeDependent()) {
  2233. QualType LHSType = TheCall->getArg(0)->getType();
  2234. QualType RHSType = TheCall->getArg(1)->getType();
  2235. if (!LHSType->isVectorType() || !RHSType->isVectorType())
  2236. return ExprError(Diag(TheCall->getLocStart(),
  2237. diag::err_shufflevector_non_vector)
  2238. << SourceRange(TheCall->getArg(0)->getLocStart(),
  2239. TheCall->getArg(1)->getLocEnd()));
  2240. numElements = LHSType->getAs<VectorType>()->getNumElements();
  2241. unsigned numResElements = TheCall->getNumArgs() - 2;
  2242. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  2243. // with mask. If so, verify that RHS is an integer vector type with the
  2244. // same number of elts as lhs.
  2245. if (TheCall->getNumArgs() == 2) {
  2246. if (!RHSType->hasIntegerRepresentation() ||
  2247. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  2248. return ExprError(Diag(TheCall->getLocStart(),
  2249. diag::err_shufflevector_incompatible_vector)
  2250. << SourceRange(TheCall->getArg(1)->getLocStart(),
  2251. TheCall->getArg(1)->getLocEnd()));
  2252. } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  2253. return ExprError(Diag(TheCall->getLocStart(),
  2254. diag::err_shufflevector_incompatible_vector)
  2255. << SourceRange(TheCall->getArg(0)->getLocStart(),
  2256. TheCall->getArg(1)->getLocEnd()));
  2257. } else if (numElements != numResElements) {
  2258. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  2259. resType = Context.getVectorType(eltType, numResElements,
  2260. VectorType::GenericVector);
  2261. }
  2262. }
  2263. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  2264. if (TheCall->getArg(i)->isTypeDependent() ||
  2265. TheCall->getArg(i)->isValueDependent())
  2266. continue;
  2267. llvm::APSInt Result(32);
  2268. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  2269. return ExprError(Diag(TheCall->getLocStart(),
  2270. diag::err_shufflevector_nonconstant_argument)
  2271. << TheCall->getArg(i)->getSourceRange());
  2272. // Allow -1 which will be translated to undef in the IR.
  2273. if (Result.isSigned() && Result.isAllOnesValue())
  2274. continue;
  2275. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  2276. return ExprError(Diag(TheCall->getLocStart(),
  2277. diag::err_shufflevector_argument_too_large)
  2278. << TheCall->getArg(i)->getSourceRange());
  2279. }
  2280. SmallVector<Expr*, 32> exprs;
  2281. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  2282. exprs.push_back(TheCall->getArg(i));
  2283. TheCall->setArg(i, nullptr);
  2284. }
  2285. return new (Context) ShuffleVectorExpr(Context, exprs, resType,
  2286. TheCall->getCallee()->getLocStart(),
  2287. TheCall->getRParenLoc());
  2288. }
  2289. /// SemaConvertVectorExpr - Handle __builtin_convertvector
  2290. ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
  2291. SourceLocation BuiltinLoc,
  2292. SourceLocation RParenLoc) {
  2293. ExprValueKind VK = VK_RValue;
  2294. ExprObjectKind OK = OK_Ordinary;
  2295. QualType DstTy = TInfo->getType();
  2296. QualType SrcTy = E->getType();
  2297. if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
  2298. return ExprError(Diag(BuiltinLoc,
  2299. diag::err_convertvector_non_vector)
  2300. << E->getSourceRange());
  2301. if (!DstTy->isVectorType() && !DstTy->isDependentType())
  2302. return ExprError(Diag(BuiltinLoc,
  2303. diag::err_convertvector_non_vector_type));
  2304. if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
  2305. unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
  2306. unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
  2307. if (SrcElts != DstElts)
  2308. return ExprError(Diag(BuiltinLoc,
  2309. diag::err_convertvector_incompatible_vector)
  2310. << E->getSourceRange());
  2311. }
  2312. return new (Context)
  2313. ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
  2314. }
  2315. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  2316. // This is declared to take (const void*, ...) and can take two
  2317. // optional constant int args.
  2318. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  2319. unsigned NumArgs = TheCall->getNumArgs();
  2320. if (NumArgs > 3)
  2321. return Diag(TheCall->getLocEnd(),
  2322. diag::err_typecheck_call_too_many_args_at_most)
  2323. << 0 /*function call*/ << 3 << NumArgs
  2324. << TheCall->getSourceRange();
  2325. // Argument 0 is checked for us and the remaining arguments must be
  2326. // constant integers.
  2327. for (unsigned i = 1; i != NumArgs; ++i)
  2328. if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
  2329. return true;
  2330. return false;
  2331. }
  2332. /// SemaBuiltinAssume - Handle __assume (MS Extension).
  2333. // __assume does not evaluate its arguments, and should warn if its argument
  2334. // has side effects.
  2335. bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
  2336. Expr *Arg = TheCall->getArg(0);
  2337. if (Arg->isInstantiationDependent()) return false;
  2338. if (Arg->HasSideEffects(Context))
  2339. Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
  2340. << Arg->getSourceRange()
  2341. << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
  2342. return false;
  2343. }
  2344. /// Handle __builtin_assume_aligned. This is declared
  2345. /// as (const void*, size_t, ...) and can take one optional constant int arg.
  2346. bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
  2347. unsigned NumArgs = TheCall->getNumArgs();
  2348. if (NumArgs > 3)
  2349. return Diag(TheCall->getLocEnd(),
  2350. diag::err_typecheck_call_too_many_args_at_most)
  2351. << 0 /*function call*/ << 3 << NumArgs
  2352. << TheCall->getSourceRange();
  2353. // The alignment must be a constant integer.
  2354. Expr *Arg = TheCall->getArg(1);
  2355. // We can't check the value of a dependent argument.
  2356. if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
  2357. llvm::APSInt Result;
  2358. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  2359. return true;
  2360. if (!Result.isPowerOf2())
  2361. return Diag(TheCall->getLocStart(),
  2362. diag::err_alignment_not_power_of_two)
  2363. << Arg->getSourceRange();
  2364. }
  2365. if (NumArgs > 2) {
  2366. ExprResult Arg(TheCall->getArg(2));
  2367. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  2368. Context.getSizeType(), false);
  2369. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  2370. if (Arg.isInvalid()) return true;
  2371. TheCall->setArg(2, Arg.get());
  2372. }
  2373. return false;
  2374. }
  2375. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  2376. /// TheCall is a constant expression.
  2377. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  2378. llvm::APSInt &Result) {
  2379. Expr *Arg = TheCall->getArg(ArgNum);
  2380. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  2381. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  2382. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  2383. if (!Arg->isIntegerConstantExpr(Result, Context))
  2384. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  2385. << FDecl->getDeclName() << Arg->getSourceRange();
  2386. return false;
  2387. }
  2388. /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
  2389. /// TheCall is a constant expression in the range [Low, High].
  2390. bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
  2391. int Low, int High) {
  2392. llvm::APSInt Result;
  2393. // We can't check the value of a dependent argument.
  2394. Expr *Arg = TheCall->getArg(ArgNum);
  2395. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2396. return false;
  2397. // Check constant-ness first.
  2398. if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
  2399. return true;
  2400. if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
  2401. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  2402. << Low << High << Arg->getSourceRange();
  2403. return false;
  2404. }
  2405. /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
  2406. /// TheCall is an ARM/AArch64 special register string literal.
  2407. bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
  2408. int ArgNum, unsigned ExpectedFieldNum,
  2409. bool AllowName) {
  2410. #if 1 // HLSL Change - remove unsupported builtins
  2411. return false;
  2412. #else
  2413. bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
  2414. BuiltinID == ARM::BI__builtin_arm_wsr64 ||
  2415. BuiltinID == ARM::BI__builtin_arm_rsr ||
  2416. BuiltinID == ARM::BI__builtin_arm_rsrp ||
  2417. BuiltinID == ARM::BI__builtin_arm_wsr ||
  2418. BuiltinID == ARM::BI__builtin_arm_wsrp;
  2419. bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
  2420. BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
  2421. BuiltinID == AArch64::BI__builtin_arm_rsr ||
  2422. BuiltinID == AArch64::BI__builtin_arm_rsrp ||
  2423. BuiltinID == AArch64::BI__builtin_arm_wsr ||
  2424. BuiltinID == AArch64::BI__builtin_arm_wsrp;
  2425. assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
  2426. // We can't check the value of a dependent argument.
  2427. Expr *Arg = TheCall->getArg(ArgNum);
  2428. if (Arg->isTypeDependent() || Arg->isValueDependent())
  2429. return false;
  2430. // Check if the argument is a string literal.
  2431. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2432. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2433. << Arg->getSourceRange();
  2434. // Check the type of special register given.
  2435. StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2436. SmallVector<StringRef, 6> Fields;
  2437. Reg.split(Fields, ":");
  2438. if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
  2439. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  2440. << Arg->getSourceRange();
  2441. // If the string is the name of a register then we cannot check that it is
  2442. // valid here but if the string is of one the forms described in ACLE then we
  2443. // can check that the supplied fields are integers and within the valid
  2444. // ranges.
  2445. if (Fields.size() > 1) {
  2446. bool FiveFields = Fields.size() == 5;
  2447. bool ValidString = true;
  2448. if (IsARMBuiltin) {
  2449. ValidString &= Fields[0].startswith_lower("cp") ||
  2450. Fields[0].startswith_lower("p");
  2451. if (ValidString)
  2452. Fields[0] =
  2453. Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
  2454. ValidString &= Fields[2].startswith_lower("c");
  2455. if (ValidString)
  2456. Fields[2] = Fields[2].drop_front(1);
  2457. if (FiveFields) {
  2458. ValidString &= Fields[3].startswith_lower("c");
  2459. if (ValidString)
  2460. Fields[3] = Fields[3].drop_front(1);
  2461. }
  2462. }
  2463. SmallVector<int, 5> Ranges;
  2464. if (FiveFields)
  2465. Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
  2466. else
  2467. Ranges.append({15, 7, 15});
  2468. for (unsigned i=0; i<Fields.size(); ++i) {
  2469. int IntField;
  2470. ValidString &= !Fields[i].getAsInteger(10, IntField);
  2471. ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
  2472. }
  2473. if (!ValidString)
  2474. return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
  2475. << Arg->getSourceRange();
  2476. } else if (IsAArch64Builtin && Fields.size() == 1) {
  2477. // If the register name is one of those that appear in the condition below
  2478. // and the special register builtin being used is one of the write builtins,
  2479. // then we require that the argument provided for writing to the register
  2480. // is an integer constant expression. This is because it will be lowered to
  2481. // an MSR (immediate) instruction, so we need to know the immediate at
  2482. // compile time.
  2483. if (TheCall->getNumArgs() != 2)
  2484. return false;
  2485. std::string RegLower = Reg.lower();
  2486. if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
  2487. RegLower != "pan" && RegLower != "uao")
  2488. return false;
  2489. return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
  2490. }
  2491. return false;
  2492. #endif // HLSL Change Ends
  2493. }
  2494. /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
  2495. /// This checks that the target supports __builtin_cpu_supports and
  2496. /// that the string argument is constant and valid.
  2497. bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
  2498. Expr *Arg = TheCall->getArg(0);
  2499. // Check if the argument is a string literal.
  2500. if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
  2501. return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
  2502. << Arg->getSourceRange();
  2503. // Check the contents of the string.
  2504. StringRef Feature =
  2505. cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
  2506. if (!Context.getTargetInfo().validateCpuSupports(Feature))
  2507. return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
  2508. << Arg->getSourceRange();
  2509. return false;
  2510. }
  2511. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  2512. /// This checks that the target supports __builtin_longjmp and
  2513. /// that val is a constant 1.
  2514. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  2515. if (!Context.getTargetInfo().hasSjLjLowering())
  2516. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
  2517. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  2518. Expr *Arg = TheCall->getArg(1);
  2519. llvm::APSInt Result;
  2520. // TODO: This is less than ideal. Overload this to take a value.
  2521. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  2522. return true;
  2523. if (Result != 1)
  2524. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  2525. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  2526. return false;
  2527. }
  2528. /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
  2529. /// This checks that the target supports __builtin_setjmp.
  2530. bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
  2531. if (!Context.getTargetInfo().hasSjLjLowering())
  2532. return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
  2533. << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
  2534. return false;
  2535. }
  2536. #if 1 // HLSL Change Starts - no support for format strings
  2537. bool Sema::hasCStrMethod(const Expr *) {
  2538. return false;
  2539. }
  2540. #else
  2541. namespace {
  2542. enum StringLiteralCheckType {
  2543. SLCT_NotALiteral,
  2544. SLCT_UncheckedLiteral,
  2545. SLCT_CheckedLiteral
  2546. };
  2547. }
  2548. // Determine if an expression is a string literal or constant string.
  2549. // If this function returns false on the arguments to a function expecting a
  2550. // format string, we will usually need to emit a warning.
  2551. // True string literals are then checked by CheckFormatString.
  2552. static StringLiteralCheckType
  2553. checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
  2554. bool HasVAListArg, unsigned format_idx,
  2555. unsigned firstDataArg, Sema::FormatStringType Type,
  2556. Sema::VariadicCallType CallType, bool InFunctionCall,
  2557. llvm::SmallBitVector &CheckedVarArgs) {
  2558. tryAgain:
  2559. if (E->isTypeDependent() || E->isValueDependent())
  2560. return SLCT_NotALiteral;
  2561. E = E->IgnoreParenCasts();
  2562. if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
  2563. // Technically -Wformat-nonliteral does not warn about this case.
  2564. // The behavior of printf and friends in this case is implementation
  2565. // dependent. Ideally if the format string cannot be null then
  2566. // it should have a 'nonnull' attribute in the function prototype.
  2567. return SLCT_UncheckedLiteral;
  2568. switch (E->getStmtClass()) {
  2569. case Stmt::BinaryConditionalOperatorClass:
  2570. case Stmt::ConditionalOperatorClass: {
  2571. // The expression is a literal if both sub-expressions were, and it was
  2572. // completely checked only if both sub-expressions were checked.
  2573. const AbstractConditionalOperator *C =
  2574. cast<AbstractConditionalOperator>(E);
  2575. StringLiteralCheckType Left =
  2576. checkFormatStringExpr(S, C->getTrueExpr(), Args,
  2577. HasVAListArg, format_idx, firstDataArg,
  2578. Type, CallType, InFunctionCall, CheckedVarArgs);
  2579. if (Left == SLCT_NotALiteral)
  2580. return SLCT_NotALiteral;
  2581. StringLiteralCheckType Right =
  2582. checkFormatStringExpr(S, C->getFalseExpr(), Args,
  2583. HasVAListArg, format_idx, firstDataArg,
  2584. Type, CallType, InFunctionCall, CheckedVarArgs);
  2585. return Left < Right ? Left : Right;
  2586. }
  2587. case Stmt::ImplicitCastExprClass: {
  2588. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  2589. goto tryAgain;
  2590. }
  2591. case Stmt::OpaqueValueExprClass:
  2592. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  2593. E = src;
  2594. goto tryAgain;
  2595. }
  2596. return SLCT_NotALiteral;
  2597. case Stmt::PredefinedExprClass:
  2598. // While __func__, etc., are technically not string literals, they
  2599. // cannot contain format specifiers and thus are not a security
  2600. // liability.
  2601. return SLCT_UncheckedLiteral;
  2602. case Stmt::DeclRefExprClass: {
  2603. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  2604. // As an exception, do not flag errors for variables binding to
  2605. // const string literals.
  2606. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  2607. bool isConstant = false;
  2608. QualType T = DR->getType();
  2609. if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
  2610. isConstant = AT->getElementType().isConstant(S.Context);
  2611. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  2612. isConstant = T.isConstant(S.Context) &&
  2613. PT->getPointeeType().isConstant(S.Context);
  2614. } else if (T->isObjCObjectPointerType()) {
  2615. // In ObjC, there is usually no "const ObjectPointer" type,
  2616. // so don't check if the pointee type is constant.
  2617. isConstant = T.isConstant(S.Context);
  2618. }
  2619. if (isConstant) {
  2620. if (const Expr *Init = VD->getAnyInitializer()) {
  2621. // Look through initializers like const char c[] = { "foo" }
  2622. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  2623. if (InitList->isStringLiteralInit())
  2624. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  2625. }
  2626. return checkFormatStringExpr(S, Init, Args,
  2627. HasVAListArg, format_idx,
  2628. firstDataArg, Type, CallType,
  2629. /*InFunctionCall*/false, CheckedVarArgs);
  2630. }
  2631. }
  2632. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  2633. // special check to see if the format string is a function parameter
  2634. // of the function calling the printf function. If the function
  2635. // has an attribute indicating it is a printf-like function, then we
  2636. // should suppress warnings concerning non-literals being used in a call
  2637. // to a vprintf function. For example:
  2638. //
  2639. // void
  2640. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  2641. // va_list ap;
  2642. // va_start(ap, fmt);
  2643. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  2644. // ...
  2645. // }
  2646. if (HasVAListArg) {
  2647. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  2648. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  2649. int PVIndex = PV->getFunctionScopeIndex() + 1;
  2650. for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
  2651. // adjust for implicit parameter
  2652. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  2653. if (MD->isInstance())
  2654. ++PVIndex;
  2655. // We also check if the formats are compatible.
  2656. // We can't pass a 'scanf' string to a 'printf' function.
  2657. if (PVIndex == PVFormat->getFormatIdx() &&
  2658. Type == S.GetFormatStringType(PVFormat))
  2659. return SLCT_UncheckedLiteral;
  2660. }
  2661. }
  2662. }
  2663. }
  2664. }
  2665. return SLCT_NotALiteral;
  2666. }
  2667. case Stmt::CallExprClass:
  2668. case Stmt::CXXMemberCallExprClass: {
  2669. const CallExpr *CE = cast<CallExpr>(E);
  2670. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  2671. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  2672. unsigned ArgIndex = FA->getFormatIdx();
  2673. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  2674. if (MD->isInstance())
  2675. --ArgIndex;
  2676. const Expr *Arg = CE->getArg(ArgIndex - 1);
  2677. return checkFormatStringExpr(S, Arg, Args,
  2678. HasVAListArg, format_idx, firstDataArg,
  2679. Type, CallType, InFunctionCall,
  2680. CheckedVarArgs);
  2681. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  2682. unsigned BuiltinID = FD->getBuiltinID();
  2683. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  2684. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  2685. const Expr *Arg = CE->getArg(0);
  2686. return checkFormatStringExpr(S, Arg, Args,
  2687. HasVAListArg, format_idx,
  2688. firstDataArg, Type, CallType,
  2689. InFunctionCall, CheckedVarArgs);
  2690. }
  2691. }
  2692. }
  2693. return SLCT_NotALiteral;
  2694. }
  2695. case Stmt::ObjCStringLiteralClass:
  2696. case Stmt::StringLiteralClass: {
  2697. const StringLiteral *StrE = nullptr;
  2698. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  2699. StrE = ObjCFExpr->getString();
  2700. else
  2701. StrE = cast<StringLiteral>(E);
  2702. if (StrE) {
  2703. S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
  2704. Type, InFunctionCall, CallType, CheckedVarArgs);
  2705. return SLCT_CheckedLiteral;
  2706. }
  2707. return SLCT_NotALiteral;
  2708. }
  2709. default:
  2710. return SLCT_NotALiteral;
  2711. }
  2712. }
  2713. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  2714. return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
  2715. .Case("scanf", FST_Scanf)
  2716. .Cases("printf", "printf0", FST_Printf)
  2717. .Cases("NSString", "CFString", FST_NSString)
  2718. .Case("strftime", FST_Strftime)
  2719. .Case("strfmon", FST_Strfmon)
  2720. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  2721. .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
  2722. .Case("os_trace", FST_OSTrace)
  2723. .Default(FST_Unknown);
  2724. }
  2725. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  2726. /// functions) for correct use of format strings.
  2727. /// Returns true if a format string has been fully checked.
  2728. bool Sema::CheckFormatArguments(const FormatAttr *Format,
  2729. ArrayRef<const Expr *> Args,
  2730. bool IsCXXMember,
  2731. VariadicCallType CallType,
  2732. SourceLocation Loc, SourceRange Range,
  2733. llvm::SmallBitVector &CheckedVarArgs) {
  2734. FormatStringInfo FSI;
  2735. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  2736. return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
  2737. FSI.FirstDataArg, GetFormatStringType(Format),
  2738. CallType, Loc, Range, CheckedVarArgs);
  2739. return false;
  2740. }
  2741. bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
  2742. bool HasVAListArg, unsigned format_idx,
  2743. unsigned firstDataArg, FormatStringType Type,
  2744. VariadicCallType CallType,
  2745. SourceLocation Loc, SourceRange Range,
  2746. llvm::SmallBitVector &CheckedVarArgs) {
  2747. // CHECK: printf/scanf-like function is called with no format string.
  2748. if (format_idx >= Args.size()) {
  2749. Diag(Loc, diag::warn_missing_format_string) << Range;
  2750. return false;
  2751. }
  2752. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  2753. // CHECK: format string is not a string literal.
  2754. //
  2755. // Dynamically generated format strings are difficult to
  2756. // automatically vet at compile time. Requiring that format strings
  2757. // are string literals: (1) permits the checking of format strings by
  2758. // the compiler and thereby (2) can practically remove the source of
  2759. // many format string exploits.
  2760. // Format string can be either ObjC string (e.g. @"%d") or
  2761. // C string (e.g. "%d")
  2762. // ObjC string uses the same format specifiers as C string, so we can use
  2763. // the same format string checking logic for both ObjC and C strings.
  2764. StringLiteralCheckType CT =
  2765. checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
  2766. format_idx, firstDataArg, Type, CallType,
  2767. /*IsFunctionCall*/true, CheckedVarArgs);
  2768. if (CT != SLCT_NotALiteral)
  2769. // Literal format string found, check done!
  2770. return CT == SLCT_CheckedLiteral;
  2771. // Strftime is particular as it always uses a single 'time' argument,
  2772. // so it is safe to pass a non-literal string.
  2773. if (Type == FST_Strftime)
  2774. return false;
  2775. // Do not emit diag when the string param is a macro expansion and the
  2776. // format is either NSString or CFString. This is a hack to prevent
  2777. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  2778. // which are usually used in place of NS and CF string literals.
  2779. if (Type == FST_NSString &&
  2780. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  2781. return false;
  2782. // If there are no arguments specified, warn with -Wformat-security, otherwise
  2783. // warn only with -Wformat-nonliteral.
  2784. if (Args.size() == firstDataArg)
  2785. Diag(Args[format_idx]->getLocStart(),
  2786. diag::warn_format_nonliteral_noargs)
  2787. << OrigFormatExpr->getSourceRange();
  2788. else
  2789. Diag(Args[format_idx]->getLocStart(),
  2790. diag::warn_format_nonliteral)
  2791. << OrigFormatExpr->getSourceRange();
  2792. return false;
  2793. }
  2794. namespace {
  2795. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  2796. protected:
  2797. Sema &S;
  2798. const StringLiteral *FExpr;
  2799. const Expr *OrigFormatExpr;
  2800. const unsigned FirstDataArg;
  2801. const unsigned NumDataArgs;
  2802. const char *Beg; // Start of format string.
  2803. const bool HasVAListArg;
  2804. ArrayRef<const Expr *> Args;
  2805. unsigned FormatIdx;
  2806. llvm::SmallBitVector CoveredArgs;
  2807. bool usesPositionalArgs;
  2808. bool atFirstArg;
  2809. bool inFunctionCall;
  2810. Sema::VariadicCallType CallType;
  2811. llvm::SmallBitVector &CheckedVarArgs;
  2812. public:
  2813. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  2814. const Expr *origFormatExpr, unsigned firstDataArg,
  2815. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2816. ArrayRef<const Expr *> Args,
  2817. unsigned formatIdx, bool inFunctionCall,
  2818. Sema::VariadicCallType callType,
  2819. llvm::SmallBitVector &CheckedVarArgs)
  2820. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  2821. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  2822. Beg(beg), HasVAListArg(hasVAListArg),
  2823. Args(Args), FormatIdx(formatIdx),
  2824. usesPositionalArgs(false), atFirstArg(true),
  2825. inFunctionCall(inFunctionCall), CallType(callType),
  2826. CheckedVarArgs(CheckedVarArgs) {
  2827. CoveredArgs.resize(numDataArgs);
  2828. CoveredArgs.reset();
  2829. }
  2830. void DoneProcessing();
  2831. void HandleIncompleteSpecifier(const char *startSpecifier,
  2832. unsigned specifierLen) override;
  2833. void HandleInvalidLengthModifier(
  2834. const analyze_format_string::FormatSpecifier &FS,
  2835. const analyze_format_string::ConversionSpecifier &CS,
  2836. const char *startSpecifier, unsigned specifierLen,
  2837. unsigned DiagID);
  2838. void HandleNonStandardLengthModifier(
  2839. const analyze_format_string::FormatSpecifier &FS,
  2840. const char *startSpecifier, unsigned specifierLen);
  2841. void HandleNonStandardConversionSpecifier(
  2842. const analyze_format_string::ConversionSpecifier &CS,
  2843. const char *startSpecifier, unsigned specifierLen);
  2844. void HandlePosition(const char *startPos, unsigned posLen) override;
  2845. void HandleInvalidPosition(const char *startSpecifier,
  2846. unsigned specifierLen,
  2847. analyze_format_string::PositionContext p) override;
  2848. void HandleZeroPosition(const char *startPos, unsigned posLen) override;
  2849. void HandleNullChar(const char *nullCharacter) override;
  2850. template <typename Range>
  2851. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  2852. const Expr *ArgumentExpr,
  2853. PartialDiagnostic PDiag,
  2854. SourceLocation StringLoc,
  2855. bool IsStringLocation, Range StringRange,
  2856. ArrayRef<FixItHint> Fixit = None);
  2857. protected:
  2858. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  2859. const char *startSpec,
  2860. unsigned specifierLen,
  2861. const char *csStart, unsigned csLen);
  2862. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  2863. const char *startSpec,
  2864. unsigned specifierLen);
  2865. SourceRange getFormatStringRange();
  2866. CharSourceRange getSpecifierRange(const char *startSpecifier,
  2867. unsigned specifierLen);
  2868. SourceLocation getLocationOfByte(const char *x);
  2869. const Expr *getDataArg(unsigned i) const;
  2870. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  2871. const analyze_format_string::ConversionSpecifier &CS,
  2872. const char *startSpecifier, unsigned specifierLen,
  2873. unsigned argIndex);
  2874. template <typename Range>
  2875. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  2876. bool IsStringLocation, Range StringRange,
  2877. ArrayRef<FixItHint> Fixit = None);
  2878. };
  2879. }
  2880. SourceRange CheckFormatHandler::getFormatStringRange() {
  2881. return OrigFormatExpr->getSourceRange();
  2882. }
  2883. CharSourceRange CheckFormatHandler::
  2884. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  2885. SourceLocation Start = getLocationOfByte(startSpecifier);
  2886. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  2887. // Advance the end SourceLocation by one due to half-open ranges.
  2888. End = End.getLocWithOffset(1);
  2889. return CharSourceRange::getCharRange(Start, End);
  2890. }
  2891. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  2892. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  2893. }
  2894. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  2895. unsigned specifierLen){
  2896. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  2897. getLocationOfByte(startSpecifier),
  2898. /*IsStringLocation*/true,
  2899. getSpecifierRange(startSpecifier, specifierLen));
  2900. }
  2901. void CheckFormatHandler::HandleInvalidLengthModifier(
  2902. const analyze_format_string::FormatSpecifier &FS,
  2903. const analyze_format_string::ConversionSpecifier &CS,
  2904. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  2905. using namespace analyze_format_string;
  2906. const LengthModifier &LM = FS.getLengthModifier();
  2907. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2908. // See if we know how to fix this length modifier.
  2909. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2910. if (FixedLM) {
  2911. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2912. getLocationOfByte(LM.getStart()),
  2913. /*IsStringLocation*/true,
  2914. getSpecifierRange(startSpecifier, specifierLen));
  2915. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2916. << FixedLM->toString()
  2917. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2918. } else {
  2919. FixItHint Hint;
  2920. if (DiagID == diag::warn_format_nonsensical_length)
  2921. Hint = FixItHint::CreateRemoval(LMRange);
  2922. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  2923. getLocationOfByte(LM.getStart()),
  2924. /*IsStringLocation*/true,
  2925. getSpecifierRange(startSpecifier, specifierLen),
  2926. Hint);
  2927. }
  2928. }
  2929. void CheckFormatHandler::HandleNonStandardLengthModifier(
  2930. const analyze_format_string::FormatSpecifier &FS,
  2931. const char *startSpecifier, unsigned specifierLen) {
  2932. using namespace analyze_format_string;
  2933. const LengthModifier &LM = FS.getLengthModifier();
  2934. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  2935. // See if we know how to fix this length modifier.
  2936. Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  2937. if (FixedLM) {
  2938. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2939. << LM.toString() << 0,
  2940. getLocationOfByte(LM.getStart()),
  2941. /*IsStringLocation*/true,
  2942. getSpecifierRange(startSpecifier, specifierLen));
  2943. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  2944. << FixedLM->toString()
  2945. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  2946. } else {
  2947. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2948. << LM.toString() << 0,
  2949. getLocationOfByte(LM.getStart()),
  2950. /*IsStringLocation*/true,
  2951. getSpecifierRange(startSpecifier, specifierLen));
  2952. }
  2953. }
  2954. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  2955. const analyze_format_string::ConversionSpecifier &CS,
  2956. const char *startSpecifier, unsigned specifierLen) {
  2957. using namespace analyze_format_string;
  2958. // See if we know how to fix this conversion specifier.
  2959. Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  2960. if (FixedCS) {
  2961. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2962. << CS.toString() << /*conversion specifier*/1,
  2963. getLocationOfByte(CS.getStart()),
  2964. /*IsStringLocation*/true,
  2965. getSpecifierRange(startSpecifier, specifierLen));
  2966. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  2967. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  2968. << FixedCS->toString()
  2969. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  2970. } else {
  2971. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  2972. << CS.toString() << /*conversion specifier*/1,
  2973. getLocationOfByte(CS.getStart()),
  2974. /*IsStringLocation*/true,
  2975. getSpecifierRange(startSpecifier, specifierLen));
  2976. }
  2977. }
  2978. void CheckFormatHandler::HandlePosition(const char *startPos,
  2979. unsigned posLen) {
  2980. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  2981. getLocationOfByte(startPos),
  2982. /*IsStringLocation*/true,
  2983. getSpecifierRange(startPos, posLen));
  2984. }
  2985. void
  2986. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  2987. analyze_format_string::PositionContext p) {
  2988. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  2989. << (unsigned) p,
  2990. getLocationOfByte(startPos), /*IsStringLocation*/true,
  2991. getSpecifierRange(startPos, posLen));
  2992. }
  2993. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  2994. unsigned posLen) {
  2995. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  2996. getLocationOfByte(startPos),
  2997. /*IsStringLocation*/true,
  2998. getSpecifierRange(startPos, posLen));
  2999. }
  3000. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  3001. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  3002. // The presence of a null character is likely an error.
  3003. EmitFormatDiagnostic(
  3004. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  3005. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  3006. getFormatStringRange());
  3007. }
  3008. }
  3009. // Note that this may return NULL if there was an error parsing or building
  3010. // one of the argument expressions.
  3011. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  3012. return Args[FirstDataArg + i];
  3013. }
  3014. void CheckFormatHandler::DoneProcessing() {
  3015. // Does the number of data arguments exceed the number of
  3016. // format conversions in the format string?
  3017. if (!HasVAListArg) {
  3018. // Find any arguments that weren't covered.
  3019. CoveredArgs.flip();
  3020. signed notCoveredArg = CoveredArgs.find_first();
  3021. if (notCoveredArg >= 0) {
  3022. assert((unsigned)notCoveredArg < NumDataArgs);
  3023. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  3024. SourceLocation Loc = E->getLocStart();
  3025. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  3026. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  3027. Loc, /*IsStringLocation*/false,
  3028. getFormatStringRange());
  3029. }
  3030. }
  3031. }
  3032. }
  3033. }
  3034. bool
  3035. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  3036. SourceLocation Loc,
  3037. const char *startSpec,
  3038. unsigned specifierLen,
  3039. const char *csStart,
  3040. unsigned csLen) {
  3041. bool keepGoing = true;
  3042. if (argIndex < NumDataArgs) {
  3043. // Consider the argument coverered, even though the specifier doesn't
  3044. // make sense.
  3045. CoveredArgs.set(argIndex);
  3046. }
  3047. else {
  3048. // If argIndex exceeds the number of data arguments we
  3049. // don't issue a warning because that is just a cascade of warnings (and
  3050. // they may have intended '%%' anyway). We don't want to continue processing
  3051. // the format string after this point, however, as we will like just get
  3052. // gibberish when trying to match arguments.
  3053. keepGoing = false;
  3054. }
  3055. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  3056. << StringRef(csStart, csLen),
  3057. Loc, /*IsStringLocation*/true,
  3058. getSpecifierRange(startSpec, specifierLen));
  3059. return keepGoing;
  3060. }
  3061. void
  3062. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  3063. const char *startSpec,
  3064. unsigned specifierLen) {
  3065. EmitFormatDiagnostic(
  3066. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  3067. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  3068. }
  3069. bool
  3070. CheckFormatHandler::CheckNumArgs(
  3071. const analyze_format_string::FormatSpecifier &FS,
  3072. const analyze_format_string::ConversionSpecifier &CS,
  3073. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  3074. if (argIndex >= NumDataArgs) {
  3075. PartialDiagnostic PDiag = FS.usesPositionalArg()
  3076. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  3077. << (argIndex+1) << NumDataArgs)
  3078. : S.PDiag(diag::warn_printf_insufficient_data_args);
  3079. EmitFormatDiagnostic(
  3080. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  3081. getSpecifierRange(startSpecifier, specifierLen));
  3082. return false;
  3083. }
  3084. return true;
  3085. }
  3086. template<typename Range>
  3087. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  3088. SourceLocation Loc,
  3089. bool IsStringLocation,
  3090. Range StringRange,
  3091. ArrayRef<FixItHint> FixIt) {
  3092. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  3093. Loc, IsStringLocation, StringRange, FixIt);
  3094. }
  3095. /// \brief If the format string is not within the funcion call, emit a note
  3096. /// so that the function call and string are in diagnostic messages.
  3097. ///
  3098. /// \param InFunctionCall if true, the format string is within the function
  3099. /// call and only one diagnostic message will be produced. Otherwise, an
  3100. /// extra note will be emitted pointing to location of the format string.
  3101. ///
  3102. /// \param ArgumentExpr the expression that is passed as the format string
  3103. /// argument in the function call. Used for getting locations when two
  3104. /// diagnostics are emitted.
  3105. ///
  3106. /// \param PDiag the callee should already have provided any strings for the
  3107. /// diagnostic message. This function only adds locations and fixits
  3108. /// to diagnostics.
  3109. ///
  3110. /// \param Loc primary location for diagnostic. If two diagnostics are
  3111. /// required, one will be at Loc and a new SourceLocation will be created for
  3112. /// the other one.
  3113. ///
  3114. /// \param IsStringLocation if true, Loc points to the format string should be
  3115. /// used for the note. Otherwise, Loc points to the argument list and will
  3116. /// be used with PDiag.
  3117. ///
  3118. /// \param StringRange some or all of the string to highlight. This is
  3119. /// templated so it can accept either a CharSourceRange or a SourceRange.
  3120. ///
  3121. /// \param FixIt optional fix it hint for the format string.
  3122. template<typename Range>
  3123. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  3124. const Expr *ArgumentExpr,
  3125. PartialDiagnostic PDiag,
  3126. SourceLocation Loc,
  3127. bool IsStringLocation,
  3128. Range StringRange,
  3129. ArrayRef<FixItHint> FixIt) {
  3130. if (InFunctionCall) {
  3131. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  3132. D << StringRange;
  3133. D << FixIt;
  3134. } else {
  3135. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  3136. << ArgumentExpr->getSourceRange();
  3137. const Sema::SemaDiagnosticBuilder &Note =
  3138. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  3139. diag::note_format_string_defined);
  3140. Note << StringRange;
  3141. Note << FixIt;
  3142. }
  3143. }
  3144. //===--- CHECK: Printf format string checking ------------------------------===//
  3145. namespace {
  3146. class CheckPrintfHandler : public CheckFormatHandler {
  3147. bool ObjCContext;
  3148. public:
  3149. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  3150. const Expr *origFormatExpr, unsigned firstDataArg,
  3151. unsigned numDataArgs, bool isObjC,
  3152. const char *beg, bool hasVAListArg,
  3153. ArrayRef<const Expr *> Args,
  3154. unsigned formatIdx, bool inFunctionCall,
  3155. Sema::VariadicCallType CallType,
  3156. llvm::SmallBitVector &CheckedVarArgs)
  3157. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  3158. numDataArgs, beg, hasVAListArg, Args,
  3159. formatIdx, inFunctionCall, CallType, CheckedVarArgs),
  3160. ObjCContext(isObjC)
  3161. {}
  3162. bool HandleInvalidPrintfConversionSpecifier(
  3163. const analyze_printf::PrintfSpecifier &FS,
  3164. const char *startSpecifier,
  3165. unsigned specifierLen) override;
  3166. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  3167. const char *startSpecifier,
  3168. unsigned specifierLen) override;
  3169. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  3170. const char *StartSpecifier,
  3171. unsigned SpecifierLen,
  3172. const Expr *E);
  3173. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  3174. const char *startSpecifier, unsigned specifierLen);
  3175. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  3176. const analyze_printf::OptionalAmount &Amt,
  3177. unsigned type,
  3178. const char *startSpecifier, unsigned specifierLen);
  3179. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  3180. const analyze_printf::OptionalFlag &flag,
  3181. const char *startSpecifier, unsigned specifierLen);
  3182. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  3183. const analyze_printf::OptionalFlag &ignoredFlag,
  3184. const analyze_printf::OptionalFlag &flag,
  3185. const char *startSpecifier, unsigned specifierLen);
  3186. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  3187. const Expr *E);
  3188. void HandleEmptyObjCModifierFlag(const char *startFlag,
  3189. unsigned flagLen) override;
  3190. void HandleInvalidObjCModifierFlag(const char *startFlag,
  3191. unsigned flagLen) override;
  3192. void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
  3193. const char *flagsEnd,
  3194. const char *conversionPosition)
  3195. override;
  3196. };
  3197. }
  3198. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  3199. const analyze_printf::PrintfSpecifier &FS,
  3200. const char *startSpecifier,
  3201. unsigned specifierLen) {
  3202. const analyze_printf::PrintfConversionSpecifier &CS =
  3203. FS.getConversionSpecifier();
  3204. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  3205. getLocationOfByte(CS.getStart()),
  3206. startSpecifier, specifierLen,
  3207. CS.getStart(), CS.getLength());
  3208. }
  3209. bool CheckPrintfHandler::HandleAmount(
  3210. const analyze_format_string::OptionalAmount &Amt,
  3211. unsigned k, const char *startSpecifier,
  3212. unsigned specifierLen) {
  3213. if (Amt.hasDataArgument()) {
  3214. if (!HasVAListArg) {
  3215. unsigned argIndex = Amt.getArgIndex();
  3216. if (argIndex >= NumDataArgs) {
  3217. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  3218. << k,
  3219. getLocationOfByte(Amt.getStart()),
  3220. /*IsStringLocation*/true,
  3221. getSpecifierRange(startSpecifier, specifierLen));
  3222. // Don't do any more checking. We will just emit
  3223. // spurious errors.
  3224. return false;
  3225. }
  3226. // Type check the data argument. It should be an 'int'.
  3227. // Although not in conformance with C99, we also allow the argument to be
  3228. // an 'unsigned int' as that is a reasonably safe case. GCC also
  3229. // doesn't emit a warning for that case.
  3230. CoveredArgs.set(argIndex);
  3231. const Expr *Arg = getDataArg(argIndex);
  3232. if (!Arg)
  3233. return false;
  3234. QualType T = Arg->getType();
  3235. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  3236. assert(AT.isValid());
  3237. if (!AT.matchesType(S.Context, T)) {
  3238. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  3239. << k << AT.getRepresentativeTypeName(S.Context)
  3240. << T << Arg->getSourceRange(),
  3241. getLocationOfByte(Amt.getStart()),
  3242. /*IsStringLocation*/true,
  3243. getSpecifierRange(startSpecifier, specifierLen));
  3244. // Don't do any more checking. We will just emit
  3245. // spurious errors.
  3246. return false;
  3247. }
  3248. }
  3249. }
  3250. return true;
  3251. }
  3252. void CheckPrintfHandler::HandleInvalidAmount(
  3253. const analyze_printf::PrintfSpecifier &FS,
  3254. const analyze_printf::OptionalAmount &Amt,
  3255. unsigned type,
  3256. const char *startSpecifier,
  3257. unsigned specifierLen) {
  3258. const analyze_printf::PrintfConversionSpecifier &CS =
  3259. FS.getConversionSpecifier();
  3260. FixItHint fixit =
  3261. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  3262. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  3263. Amt.getConstantLength()))
  3264. : FixItHint();
  3265. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  3266. << type << CS.toString(),
  3267. getLocationOfByte(Amt.getStart()),
  3268. /*IsStringLocation*/true,
  3269. getSpecifierRange(startSpecifier, specifierLen),
  3270. fixit);
  3271. }
  3272. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  3273. const analyze_printf::OptionalFlag &flag,
  3274. const char *startSpecifier,
  3275. unsigned specifierLen) {
  3276. // Warn about pointless flag with a fixit removal.
  3277. const analyze_printf::PrintfConversionSpecifier &CS =
  3278. FS.getConversionSpecifier();
  3279. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  3280. << flag.toString() << CS.toString(),
  3281. getLocationOfByte(flag.getPosition()),
  3282. /*IsStringLocation*/true,
  3283. getSpecifierRange(startSpecifier, specifierLen),
  3284. FixItHint::CreateRemoval(
  3285. getSpecifierRange(flag.getPosition(), 1)));
  3286. }
  3287. void CheckPrintfHandler::HandleIgnoredFlag(
  3288. const analyze_printf::PrintfSpecifier &FS,
  3289. const analyze_printf::OptionalFlag &ignoredFlag,
  3290. const analyze_printf::OptionalFlag &flag,
  3291. const char *startSpecifier,
  3292. unsigned specifierLen) {
  3293. // Warn about ignored flag with a fixit removal.
  3294. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  3295. << ignoredFlag.toString() << flag.toString(),
  3296. getLocationOfByte(ignoredFlag.getPosition()),
  3297. /*IsStringLocation*/true,
  3298. getSpecifierRange(startSpecifier, specifierLen),
  3299. FixItHint::CreateRemoval(
  3300. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  3301. }
  3302. // void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  3303. // bool IsStringLocation, Range StringRange,
  3304. // ArrayRef<FixItHint> Fixit = None);
  3305. void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
  3306. unsigned flagLen) {
  3307. // Warn about an empty flag.
  3308. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
  3309. getLocationOfByte(startFlag),
  3310. /*IsStringLocation*/true,
  3311. getSpecifierRange(startFlag, flagLen));
  3312. }
  3313. void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
  3314. unsigned flagLen) {
  3315. // Warn about an invalid flag.
  3316. auto Range = getSpecifierRange(startFlag, flagLen);
  3317. StringRef flag(startFlag, flagLen);
  3318. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
  3319. getLocationOfByte(startFlag),
  3320. /*IsStringLocation*/true,
  3321. Range, FixItHint::CreateRemoval(Range));
  3322. }
  3323. void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
  3324. const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
  3325. // Warn about using '[...]' without a '@' conversion.
  3326. auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
  3327. auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
  3328. EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
  3329. getLocationOfByte(conversionPosition),
  3330. /*IsStringLocation*/true,
  3331. Range, FixItHint::CreateRemoval(Range));
  3332. }
  3333. // Determines if the specified is a C++ class or struct containing
  3334. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  3335. // "c_str()").
  3336. template<typename MemberKind>
  3337. static llvm::SmallPtrSet<MemberKind*, 1>
  3338. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  3339. const RecordType *RT = Ty->getAs<RecordType>();
  3340. llvm::SmallPtrSet<MemberKind*, 1> Results;
  3341. if (!RT)
  3342. return Results;
  3343. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  3344. if (!RD || !RD->getDefinition())
  3345. return Results;
  3346. LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
  3347. Sema::LookupMemberName);
  3348. R.suppressDiagnostics();
  3349. // We just need to include all members of the right kind turned up by the
  3350. // filter, at this point.
  3351. if (S.LookupQualifiedName(R, RT->getDecl()))
  3352. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  3353. NamedDecl *decl = (*I)->getUnderlyingDecl();
  3354. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  3355. Results.insert(FK);
  3356. }
  3357. return Results;
  3358. }
  3359. /// Check if we could call '.c_str()' on an object.
  3360. ///
  3361. /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
  3362. /// allow the call, or if it would be ambiguous).
  3363. bool Sema::hasCStrMethod(const Expr *E) {
  3364. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  3365. MethodSet Results =
  3366. CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
  3367. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  3368. MI != ME; ++MI)
  3369. if ((*MI)->getMinRequiredArguments() == 0)
  3370. return true;
  3371. return false;
  3372. }
  3373. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  3374. // better diagnostic if so. AT is assumed to be valid.
  3375. // Returns true when a c_str() conversion method is found.
  3376. bool CheckPrintfHandler::checkForCStrMembers(
  3377. const analyze_printf::ArgType &AT, const Expr *E) {
  3378. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  3379. MethodSet Results =
  3380. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  3381. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  3382. MI != ME; ++MI) {
  3383. const CXXMethodDecl *Method = *MI;
  3384. if (Method->getMinRequiredArguments() == 0 &&
  3385. AT.matchesType(S.Context, Method->getReturnType())) {
  3386. // FIXME: Suggest parens if the expression needs them.
  3387. SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
  3388. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  3389. << "c_str()"
  3390. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  3391. return true;
  3392. }
  3393. }
  3394. return false;
  3395. }
  3396. bool
  3397. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  3398. &FS,
  3399. const char *startSpecifier,
  3400. unsigned specifierLen) {
  3401. using namespace analyze_format_string;
  3402. using namespace analyze_printf;
  3403. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  3404. if (FS.consumesDataArgument()) {
  3405. if (atFirstArg) {
  3406. atFirstArg = false;
  3407. usesPositionalArgs = FS.usesPositionalArg();
  3408. }
  3409. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  3410. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  3411. startSpecifier, specifierLen);
  3412. return false;
  3413. }
  3414. }
  3415. // First check if the field width, precision, and conversion specifier
  3416. // have matching data arguments.
  3417. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  3418. startSpecifier, specifierLen)) {
  3419. return false;
  3420. }
  3421. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  3422. startSpecifier, specifierLen)) {
  3423. return false;
  3424. }
  3425. if (!CS.consumesDataArgument()) {
  3426. // FIXME: Technically specifying a precision or field width here
  3427. // makes no sense. Worth issuing a warning at some point.
  3428. return true;
  3429. }
  3430. // Consume the argument.
  3431. unsigned argIndex = FS.getArgIndex();
  3432. if (argIndex < NumDataArgs) {
  3433. // The check to see if the argIndex is valid will come later.
  3434. // We set the bit here because we may exit early from this
  3435. // function if we encounter some other error.
  3436. CoveredArgs.set(argIndex);
  3437. }
  3438. // FreeBSD kernel extensions.
  3439. if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
  3440. CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
  3441. // We need at least two arguments.
  3442. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
  3443. return false;
  3444. // Claim the second argument.
  3445. CoveredArgs.set(argIndex + 1);
  3446. // Type check the first argument (int for %b, pointer for %D)
  3447. const Expr *Ex = getDataArg(argIndex);
  3448. const analyze_printf::ArgType &AT =
  3449. (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
  3450. ArgType(S.Context.IntTy) : ArgType::CPointerTy;
  3451. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
  3452. EmitFormatDiagnostic(
  3453. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3454. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  3455. << false << Ex->getSourceRange(),
  3456. Ex->getLocStart(), /*IsStringLocation*/false,
  3457. getSpecifierRange(startSpecifier, specifierLen));
  3458. // Type check the second argument (char * for both %b and %D)
  3459. Ex = getDataArg(argIndex + 1);
  3460. const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
  3461. if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
  3462. EmitFormatDiagnostic(
  3463. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3464. << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
  3465. << false << Ex->getSourceRange(),
  3466. Ex->getLocStart(), /*IsStringLocation*/false,
  3467. getSpecifierRange(startSpecifier, specifierLen));
  3468. return true;
  3469. }
  3470. // Check for using an Objective-C specific conversion specifier
  3471. // in a non-ObjC literal.
  3472. if (!ObjCContext && CS.isObjCArg()) {
  3473. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  3474. specifierLen);
  3475. }
  3476. // Check for invalid use of field width
  3477. if (!FS.hasValidFieldWidth()) {
  3478. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  3479. startSpecifier, specifierLen);
  3480. }
  3481. // Check for invalid use of precision
  3482. if (!FS.hasValidPrecision()) {
  3483. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  3484. startSpecifier, specifierLen);
  3485. }
  3486. // Check each flag does not conflict with any other component.
  3487. if (!FS.hasValidThousandsGroupingPrefix())
  3488. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  3489. if (!FS.hasValidLeadingZeros())
  3490. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  3491. if (!FS.hasValidPlusPrefix())
  3492. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  3493. if (!FS.hasValidSpacePrefix())
  3494. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  3495. if (!FS.hasValidAlternativeForm())
  3496. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  3497. if (!FS.hasValidLeftJustified())
  3498. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  3499. // Check that flags are not ignored by another flag
  3500. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  3501. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  3502. startSpecifier, specifierLen);
  3503. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  3504. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  3505. startSpecifier, specifierLen);
  3506. // Check the length modifier is valid with the given conversion specifier.
  3507. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3508. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3509. diag::warn_format_nonsensical_length);
  3510. else if (!FS.hasStandardLengthModifier())
  3511. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3512. else if (!FS.hasStandardLengthConversionCombination())
  3513. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3514. diag::warn_format_non_standard_conversion_spec);
  3515. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3516. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3517. // The remaining checks depend on the data arguments.
  3518. if (HasVAListArg)
  3519. return true;
  3520. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3521. return false;
  3522. const Expr *Arg = getDataArg(argIndex);
  3523. if (!Arg)
  3524. return true;
  3525. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  3526. }
  3527. static bool requiresParensToAddCast(const Expr *E) {
  3528. // FIXME: We should have a general way to reason about operator
  3529. // precedence and whether parens are actually needed here.
  3530. // Take care of a few common cases where they aren't.
  3531. const Expr *Inside = E->IgnoreImpCasts();
  3532. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  3533. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  3534. switch (Inside->getStmtClass()) {
  3535. case Stmt::ArraySubscriptExprClass:
  3536. case Stmt::CallExprClass:
  3537. case Stmt::CharacterLiteralClass:
  3538. case Stmt::CXXBoolLiteralExprClass:
  3539. case Stmt::DeclRefExprClass:
  3540. case Stmt::FloatingLiteralClass:
  3541. case Stmt::IntegerLiteralClass:
  3542. case Stmt::MemberExprClass:
  3543. case Stmt::ObjCArrayLiteralClass:
  3544. case Stmt::ObjCBoolLiteralExprClass:
  3545. case Stmt::ObjCBoxedExprClass:
  3546. case Stmt::ObjCDictionaryLiteralClass:
  3547. case Stmt::ObjCEncodeExprClass:
  3548. case Stmt::ObjCIvarRefExprClass:
  3549. case Stmt::ObjCMessageExprClass:
  3550. case Stmt::ObjCPropertyRefExprClass:
  3551. case Stmt::ObjCStringLiteralClass:
  3552. case Stmt::ObjCSubscriptRefExprClass:
  3553. case Stmt::ParenExprClass:
  3554. case Stmt::StringLiteralClass:
  3555. case Stmt::UnaryOperatorClass:
  3556. return false;
  3557. default:
  3558. return true;
  3559. }
  3560. }
  3561. static std::pair<QualType, StringRef>
  3562. shouldNotPrintDirectly(const ASTContext &Context,
  3563. QualType IntendedTy,
  3564. const Expr *E) {
  3565. // Use a 'while' to peel off layers of typedefs.
  3566. QualType TyTy = IntendedTy;
  3567. while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
  3568. StringRef Name = UserTy->getDecl()->getName();
  3569. QualType CastTy = llvm::StringSwitch<QualType>(Name)
  3570. .Case("NSInteger", Context.LongTy)
  3571. .Case("NSUInteger", Context.UnsignedLongTy)
  3572. .Case("SInt32", Context.IntTy)
  3573. .Case("UInt32", Context.UnsignedIntTy)
  3574. .Default(QualType());
  3575. if (!CastTy.isNull())
  3576. return std::make_pair(CastTy, Name);
  3577. TyTy = UserTy->desugar();
  3578. }
  3579. // Strip parens if necessary.
  3580. if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
  3581. return shouldNotPrintDirectly(Context,
  3582. PE->getSubExpr()->getType(),
  3583. PE->getSubExpr());
  3584. // If this is a conditional expression, then its result type is constructed
  3585. // via usual arithmetic conversions and thus there might be no necessary
  3586. // typedef sugar there. Recurse to operands to check for NSInteger &
  3587. // Co. usage condition.
  3588. if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3589. QualType TrueTy, FalseTy;
  3590. StringRef TrueName, FalseName;
  3591. std::tie(TrueTy, TrueName) =
  3592. shouldNotPrintDirectly(Context,
  3593. CO->getTrueExpr()->getType(),
  3594. CO->getTrueExpr());
  3595. std::tie(FalseTy, FalseName) =
  3596. shouldNotPrintDirectly(Context,
  3597. CO->getFalseExpr()->getType(),
  3598. CO->getFalseExpr());
  3599. if (TrueTy == FalseTy)
  3600. return std::make_pair(TrueTy, TrueName);
  3601. else if (TrueTy.isNull())
  3602. return std::make_pair(FalseTy, FalseName);
  3603. else if (FalseTy.isNull())
  3604. return std::make_pair(TrueTy, TrueName);
  3605. }
  3606. return std::make_pair(QualType(), StringRef());
  3607. }
  3608. bool
  3609. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  3610. const char *StartSpecifier,
  3611. unsigned SpecifierLen,
  3612. const Expr *E) {
  3613. using namespace analyze_format_string;
  3614. using namespace analyze_printf;
  3615. // Now type check the data expression that matches the
  3616. // format specifier.
  3617. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  3618. ObjCContext);
  3619. if (!AT.isValid())
  3620. return true;
  3621. QualType ExprTy = E->getType();
  3622. while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
  3623. ExprTy = TET->getUnderlyingExpr()->getType();
  3624. }
  3625. analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
  3626. if (match == analyze_printf::ArgType::Match) {
  3627. return true;
  3628. }
  3629. // Look through argument promotions for our error message's reported type.
  3630. // This includes the integral and floating promotions, but excludes array
  3631. // and function pointer decay; seeing that an argument intended to be a
  3632. // string has type 'char [6]' is probably more confusing than 'char *'.
  3633. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3634. if (ICE->getCastKind() == CK_IntegralCast ||
  3635. ICE->getCastKind() == CK_FloatingCast) {
  3636. E = ICE->getSubExpr();
  3637. ExprTy = E->getType();
  3638. // Check if we didn't match because of an implicit cast from a 'char'
  3639. // or 'short' to an 'int'. This is done because printf is a varargs
  3640. // function.
  3641. if (ICE->getType() == S.Context.IntTy ||
  3642. ICE->getType() == S.Context.UnsignedIntTy) {
  3643. // All further checking is done on the subexpression.
  3644. if (AT.matchesType(S.Context, ExprTy))
  3645. return true;
  3646. }
  3647. }
  3648. } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
  3649. // Special case for 'a', which has type 'int' in C.
  3650. // Note, however, that we do /not/ want to treat multibyte constants like
  3651. // 'MooV' as characters! This form is deprecated but still exists.
  3652. if (ExprTy == S.Context.IntTy)
  3653. if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
  3654. ExprTy = S.Context.CharTy;
  3655. }
  3656. // Look through enums to their underlying type.
  3657. bool IsEnum = false;
  3658. if (auto EnumTy = ExprTy->getAs<EnumType>()) {
  3659. ExprTy = EnumTy->getDecl()->getIntegerType();
  3660. IsEnum = true;
  3661. }
  3662. // %C in an Objective-C context prints a unichar, not a wchar_t.
  3663. // If the argument is an integer of some kind, believe the %C and suggest
  3664. // a cast instead of changing the conversion specifier.
  3665. QualType IntendedTy = ExprTy;
  3666. if (ObjCContext &&
  3667. FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
  3668. if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
  3669. !ExprTy->isCharType()) {
  3670. // 'unichar' is defined as a typedef of unsigned short, but we should
  3671. // prefer using the typedef if it is visible.
  3672. IntendedTy = S.Context.UnsignedShortTy;
  3673. // While we are here, check if the value is an IntegerLiteral that happens
  3674. // to be within the valid range.
  3675. if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  3676. const llvm::APInt &V = IL->getValue();
  3677. if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
  3678. return true;
  3679. }
  3680. LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
  3681. Sema::LookupOrdinaryName);
  3682. if (S.LookupName(Result, S.getCurScope())) {
  3683. NamedDecl *ND = Result.getFoundDecl();
  3684. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
  3685. if (TD->getUnderlyingType() == IntendedTy)
  3686. IntendedTy = S.Context.getTypedefType(TD);
  3687. }
  3688. }
  3689. }
  3690. // Special-case some of Darwin's platform-independence types by suggesting
  3691. // casts to primitive types that are known to be large enough.
  3692. bool ShouldNotPrintDirectly = false; StringRef CastTyName;
  3693. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  3694. QualType CastTy;
  3695. std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
  3696. if (!CastTy.isNull()) {
  3697. IntendedTy = CastTy;
  3698. ShouldNotPrintDirectly = true;
  3699. }
  3700. }
  3701. // We may be able to offer a FixItHint if it is a supported type.
  3702. PrintfSpecifier fixedFS = FS;
  3703. bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
  3704. S.Context, ObjCContext);
  3705. if (success) {
  3706. // Get the fix string from the fixed format specifier
  3707. SmallString<16> buf;
  3708. llvm::raw_svector_ostream os(buf);
  3709. fixedFS.toString(os);
  3710. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  3711. if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
  3712. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3713. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  3714. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3715. }
  3716. // In this case, the specifier is wrong and should be changed to match
  3717. // the argument.
  3718. EmitFormatDiagnostic(S.PDiag(diag)
  3719. << AT.getRepresentativeTypeName(S.Context)
  3720. << IntendedTy << IsEnum << E->getSourceRange(),
  3721. E->getLocStart(),
  3722. /*IsStringLocation*/ false, SpecRange,
  3723. FixItHint::CreateReplacement(SpecRange, os.str()));
  3724. } else {
  3725. // The canonical type for formatting this value is different from the
  3726. // actual type of the expression. (This occurs, for example, with Darwin's
  3727. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  3728. // should be printed as 'long' for 64-bit compatibility.)
  3729. // Rather than emitting a normal format/argument mismatch, we want to
  3730. // add a cast to the recommended type (and correct the format string
  3731. // if necessary).
  3732. SmallString<16> CastBuf;
  3733. llvm::raw_svector_ostream CastFix(CastBuf);
  3734. CastFix << "(";
  3735. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  3736. CastFix << ")";
  3737. SmallVector<FixItHint,4> Hints;
  3738. if (!AT.matchesType(S.Context, IntendedTy))
  3739. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  3740. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  3741. // If there's already a cast present, just replace it.
  3742. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  3743. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  3744. } else if (!requiresParensToAddCast(E)) {
  3745. // If the expression has high enough precedence,
  3746. // just write the C-style cast.
  3747. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  3748. CastFix.str()));
  3749. } else {
  3750. // Otherwise, add parens around the expression as well as the cast.
  3751. CastFix << "(";
  3752. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  3753. CastFix.str()));
  3754. SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
  3755. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  3756. }
  3757. if (ShouldNotPrintDirectly) {
  3758. // The expression has a type that should not be printed directly.
  3759. // We extract the name from the typedef because we don't want to show
  3760. // the underlying type in the diagnostic.
  3761. StringRef Name;
  3762. if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
  3763. Name = TypedefTy->getDecl()->getName();
  3764. else
  3765. Name = CastTyName;
  3766. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  3767. << Name << IntendedTy << IsEnum
  3768. << E->getSourceRange(),
  3769. E->getLocStart(), /*IsStringLocation=*/false,
  3770. SpecRange, Hints);
  3771. } else {
  3772. // In this case, the expression could be printed using a different
  3773. // specifier, but we've decided that the specifier is probably correct
  3774. // and we should cast instead. Just use the normal warning message.
  3775. EmitFormatDiagnostic(
  3776. S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
  3777. << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
  3778. << E->getSourceRange(),
  3779. E->getLocStart(), /*IsStringLocation*/false,
  3780. SpecRange, Hints);
  3781. }
  3782. }
  3783. } else {
  3784. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  3785. SpecifierLen);
  3786. // Since the warning for passing non-POD types to variadic functions
  3787. // was deferred until now, we emit a warning for non-POD
  3788. // arguments here.
  3789. switch (S.isValidVarArgType(ExprTy)) {
  3790. case Sema::VAK_Valid:
  3791. case Sema::VAK_ValidInCXX11: {
  3792. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3793. if (match == analyze_printf::ArgType::NoMatchPedantic) {
  3794. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3795. }
  3796. EmitFormatDiagnostic(
  3797. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
  3798. << IsEnum << CSR << E->getSourceRange(),
  3799. E->getLocStart(), /*IsStringLocation*/ false, CSR);
  3800. break;
  3801. }
  3802. case Sema::VAK_Undefined:
  3803. case Sema::VAK_MSVCUndefined:
  3804. EmitFormatDiagnostic(
  3805. S.PDiag(diag::warn_non_pod_vararg_with_format_string)
  3806. << S.getLangOpts().CPlusPlus11
  3807. << ExprTy
  3808. << CallType
  3809. << AT.getRepresentativeTypeName(S.Context)
  3810. << CSR
  3811. << E->getSourceRange(),
  3812. E->getLocStart(), /*IsStringLocation*/false, CSR);
  3813. checkForCStrMembers(AT, E);
  3814. break;
  3815. case Sema::VAK_Invalid:
  3816. if (ExprTy->isObjCObjectType())
  3817. EmitFormatDiagnostic(
  3818. S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
  3819. << S.getLangOpts().CPlusPlus11
  3820. << ExprTy
  3821. << CallType
  3822. << AT.getRepresentativeTypeName(S.Context)
  3823. << CSR
  3824. << E->getSourceRange(),
  3825. E->getLocStart(), /*IsStringLocation*/false, CSR);
  3826. else
  3827. // FIXME: If this is an initializer list, suggest removing the braces
  3828. // or inserting a cast to the target type.
  3829. S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
  3830. << isa<InitListExpr>(E) << ExprTy << CallType
  3831. << AT.getRepresentativeTypeName(S.Context)
  3832. << E->getSourceRange();
  3833. break;
  3834. }
  3835. assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
  3836. "format string specifier index out of range");
  3837. CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
  3838. }
  3839. return true;
  3840. }
  3841. //===--- CHECK: Scanf format string checking ------------------------------===//
  3842. namespace {
  3843. class CheckScanfHandler : public CheckFormatHandler {
  3844. public:
  3845. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  3846. const Expr *origFormatExpr, unsigned firstDataArg,
  3847. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  3848. ArrayRef<const Expr *> Args,
  3849. unsigned formatIdx, bool inFunctionCall,
  3850. Sema::VariadicCallType CallType,
  3851. llvm::SmallBitVector &CheckedVarArgs)
  3852. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  3853. numDataArgs, beg, hasVAListArg,
  3854. Args, formatIdx, inFunctionCall, CallType,
  3855. CheckedVarArgs)
  3856. {}
  3857. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  3858. const char *startSpecifier,
  3859. unsigned specifierLen) override;
  3860. bool HandleInvalidScanfConversionSpecifier(
  3861. const analyze_scanf::ScanfSpecifier &FS,
  3862. const char *startSpecifier,
  3863. unsigned specifierLen) override;
  3864. void HandleIncompleteScanList(const char *start, const char *end) override;
  3865. };
  3866. }
  3867. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  3868. const char *end) {
  3869. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  3870. getLocationOfByte(end), /*IsStringLocation*/true,
  3871. getSpecifierRange(start, end - start));
  3872. }
  3873. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  3874. const analyze_scanf::ScanfSpecifier &FS,
  3875. const char *startSpecifier,
  3876. unsigned specifierLen) {
  3877. const analyze_scanf::ScanfConversionSpecifier &CS =
  3878. FS.getConversionSpecifier();
  3879. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  3880. getLocationOfByte(CS.getStart()),
  3881. startSpecifier, specifierLen,
  3882. CS.getStart(), CS.getLength());
  3883. }
  3884. bool CheckScanfHandler::HandleScanfSpecifier(
  3885. const analyze_scanf::ScanfSpecifier &FS,
  3886. const char *startSpecifier,
  3887. unsigned specifierLen) {
  3888. using namespace analyze_scanf;
  3889. using namespace analyze_format_string;
  3890. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  3891. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  3892. // be used to decide if we are using positional arguments consistently.
  3893. if (FS.consumesDataArgument()) {
  3894. if (atFirstArg) {
  3895. atFirstArg = false;
  3896. usesPositionalArgs = FS.usesPositionalArg();
  3897. }
  3898. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  3899. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  3900. startSpecifier, specifierLen);
  3901. return false;
  3902. }
  3903. }
  3904. // Check if the field with is non-zero.
  3905. const OptionalAmount &Amt = FS.getFieldWidth();
  3906. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  3907. if (Amt.getConstantAmount() == 0) {
  3908. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  3909. Amt.getConstantLength());
  3910. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  3911. getLocationOfByte(Amt.getStart()),
  3912. /*IsStringLocation*/true, R,
  3913. FixItHint::CreateRemoval(R));
  3914. }
  3915. }
  3916. if (!FS.consumesDataArgument()) {
  3917. // FIXME: Technically specifying a precision or field width here
  3918. // makes no sense. Worth issuing a warning at some point.
  3919. return true;
  3920. }
  3921. // Consume the argument.
  3922. unsigned argIndex = FS.getArgIndex();
  3923. if (argIndex < NumDataArgs) {
  3924. // The check to see if the argIndex is valid will come later.
  3925. // We set the bit here because we may exit early from this
  3926. // function if we encounter some other error.
  3927. CoveredArgs.set(argIndex);
  3928. }
  3929. // Check the length modifier is valid with the given conversion specifier.
  3930. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  3931. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3932. diag::warn_format_nonsensical_length);
  3933. else if (!FS.hasStandardLengthModifier())
  3934. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  3935. else if (!FS.hasStandardLengthConversionCombination())
  3936. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  3937. diag::warn_format_non_standard_conversion_spec);
  3938. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  3939. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  3940. // The remaining checks depend on the data arguments.
  3941. if (HasVAListArg)
  3942. return true;
  3943. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  3944. return false;
  3945. // Check that the argument type matches the format specifier.
  3946. const Expr *Ex = getDataArg(argIndex);
  3947. if (!Ex)
  3948. return true;
  3949. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  3950. if (!AT.isValid()) {
  3951. return true;
  3952. }
  3953. analyze_format_string::ArgType::MatchKind match =
  3954. AT.matchesType(S.Context, Ex->getType());
  3955. if (match == analyze_format_string::ArgType::Match) {
  3956. return true;
  3957. }
  3958. ScanfSpecifier fixedFS = FS;
  3959. bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
  3960. S.getLangOpts(), S.Context);
  3961. unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
  3962. if (match == analyze_format_string::ArgType::NoMatchPedantic) {
  3963. diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
  3964. }
  3965. if (success) {
  3966. // Get the fix string from the fixed format specifier.
  3967. SmallString<128> buf;
  3968. llvm::raw_svector_ostream os(buf);
  3969. fixedFS.toString(os);
  3970. EmitFormatDiagnostic(
  3971. S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
  3972. << Ex->getType() << false << Ex->getSourceRange(),
  3973. Ex->getLocStart(),
  3974. /*IsStringLocation*/ false,
  3975. getSpecifierRange(startSpecifier, specifierLen),
  3976. FixItHint::CreateReplacement(
  3977. getSpecifierRange(startSpecifier, specifierLen), os.str()));
  3978. } else {
  3979. EmitFormatDiagnostic(S.PDiag(diag)
  3980. << AT.getRepresentativeTypeName(S.Context)
  3981. << Ex->getType() << false << Ex->getSourceRange(),
  3982. Ex->getLocStart(),
  3983. /*IsStringLocation*/ false,
  3984. getSpecifierRange(startSpecifier, specifierLen));
  3985. }
  3986. return true;
  3987. }
  3988. void Sema::CheckFormatString(const StringLiteral *FExpr,
  3989. const Expr *OrigFormatExpr,
  3990. ArrayRef<const Expr *> Args,
  3991. bool HasVAListArg, unsigned format_idx,
  3992. unsigned firstDataArg, FormatStringType Type,
  3993. bool inFunctionCall, VariadicCallType CallType,
  3994. llvm::SmallBitVector &CheckedVarArgs) {
  3995. // CHECK: is the format string a wide literal?
  3996. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  3997. CheckFormatHandler::EmitFormatDiagnostic(
  3998. *this, inFunctionCall, Args[format_idx],
  3999. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  4000. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  4001. return;
  4002. }
  4003. // Str - The format string. NOTE: this is NOT null-terminated!
  4004. StringRef StrRef = FExpr->getString();
  4005. const char *Str = StrRef.data();
  4006. // Account for cases where the string literal is truncated in a declaration.
  4007. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  4008. assert(T && "String literal not of constant array type!");
  4009. size_t TypeSize = T->getSize().getZExtValue();
  4010. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  4011. const unsigned numDataArgs = Args.size() - firstDataArg;
  4012. // Emit a warning if the string literal is truncated and does not contain an
  4013. // embedded null character.
  4014. if (TypeSize <= StrRef.size() &&
  4015. StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
  4016. CheckFormatHandler::EmitFormatDiagnostic(
  4017. *this, inFunctionCall, Args[format_idx],
  4018. PDiag(diag::warn_printf_format_string_not_null_terminated),
  4019. FExpr->getLocStart(),
  4020. /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
  4021. return;
  4022. }
  4023. // CHECK: empty format string?
  4024. if (StrLen == 0 && numDataArgs > 0) {
  4025. CheckFormatHandler::EmitFormatDiagnostic(
  4026. *this, inFunctionCall, Args[format_idx],
  4027. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  4028. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  4029. return;
  4030. }
  4031. if (Type == FST_Printf || Type == FST_NSString ||
  4032. Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
  4033. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  4034. numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
  4035. Str, HasVAListArg, Args, format_idx,
  4036. inFunctionCall, CallType, CheckedVarArgs);
  4037. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  4038. getLangOpts(),
  4039. Context.getTargetInfo(),
  4040. Type == FST_FreeBSDKPrintf))
  4041. H.DoneProcessing();
  4042. } else if (Type == FST_Scanf) {
  4043. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  4044. Str, HasVAListArg, Args, format_idx,
  4045. inFunctionCall, CallType, CheckedVarArgs);
  4046. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  4047. getLangOpts(),
  4048. Context.getTargetInfo()))
  4049. H.DoneProcessing();
  4050. } // TODO: handle other formats
  4051. }
  4052. bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
  4053. // Str - The format string. NOTE: this is NOT null-terminated!
  4054. StringRef StrRef = FExpr->getString();
  4055. const char *Str = StrRef.data();
  4056. // Account for cases where the string literal is truncated in a declaration.
  4057. const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
  4058. assert(T && "String literal not of constant array type!");
  4059. size_t TypeSize = T->getSize().getZExtValue();
  4060. size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
  4061. return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
  4062. getLangOpts(),
  4063. Context.getTargetInfo());
  4064. }
  4065. #endif // HLSL Change - no support for format strings
  4066. //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
  4067. // Returns the related absolute value function that is larger, of 0 if one
  4068. // does not exist.
  4069. static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
  4070. switch (AbsFunction) {
  4071. default:
  4072. return 0;
  4073. case Builtin::BI__builtin_abs:
  4074. return Builtin::BI__builtin_labs;
  4075. case Builtin::BI__builtin_labs:
  4076. return Builtin::BI__builtin_llabs;
  4077. case Builtin::BI__builtin_llabs:
  4078. return 0;
  4079. case Builtin::BI__builtin_fabsf:
  4080. return Builtin::BI__builtin_fabs;
  4081. case Builtin::BI__builtin_fabs:
  4082. return Builtin::BI__builtin_fabsl;
  4083. case Builtin::BI__builtin_fabsl:
  4084. return 0;
  4085. case Builtin::BI__builtin_cabsf:
  4086. return Builtin::BI__builtin_cabs;
  4087. case Builtin::BI__builtin_cabs:
  4088. return Builtin::BI__builtin_cabsl;
  4089. case Builtin::BI__builtin_cabsl:
  4090. return 0;
  4091. case Builtin::BIabs:
  4092. return Builtin::BIlabs;
  4093. case Builtin::BIlabs:
  4094. return Builtin::BIllabs;
  4095. case Builtin::BIllabs:
  4096. return 0;
  4097. case Builtin::BIfabsf:
  4098. return Builtin::BIfabs;
  4099. case Builtin::BIfabs:
  4100. return Builtin::BIfabsl;
  4101. case Builtin::BIfabsl:
  4102. return 0;
  4103. case Builtin::BIcabsf:
  4104. return Builtin::BIcabs;
  4105. case Builtin::BIcabs:
  4106. return Builtin::BIcabsl;
  4107. case Builtin::BIcabsl:
  4108. return 0;
  4109. }
  4110. }
  4111. // Returns the argument type of the absolute value function.
  4112. static QualType getAbsoluteValueArgumentType(ASTContext &Context,
  4113. unsigned AbsType) {
  4114. if (AbsType == 0)
  4115. return QualType();
  4116. ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
  4117. QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
  4118. if (Error != ASTContext::GE_None)
  4119. return QualType();
  4120. const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
  4121. if (!FT)
  4122. return QualType();
  4123. if (FT->getNumParams() != 1)
  4124. return QualType();
  4125. return FT->getParamType(0);
  4126. }
  4127. // Returns the best absolute value function, or zero, based on type and
  4128. // current absolute value function.
  4129. static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
  4130. unsigned AbsFunctionKind) {
  4131. unsigned BestKind = 0;
  4132. uint64_t ArgSize = Context.getTypeSize(ArgType);
  4133. for (unsigned Kind = AbsFunctionKind; Kind != 0;
  4134. Kind = getLargerAbsoluteValueFunction(Kind)) {
  4135. QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
  4136. if (Context.getTypeSize(ParamType) >= ArgSize) {
  4137. if (BestKind == 0)
  4138. BestKind = Kind;
  4139. else if (Context.hasSameType(ParamType, ArgType)) {
  4140. BestKind = Kind;
  4141. break;
  4142. }
  4143. }
  4144. }
  4145. return BestKind;
  4146. }
  4147. enum AbsoluteValueKind {
  4148. AVK_Integer,
  4149. AVK_Floating,
  4150. AVK_Complex
  4151. };
  4152. static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
  4153. if (T->isIntegralOrEnumerationType())
  4154. return AVK_Integer;
  4155. if (T->isRealFloatingType())
  4156. return AVK_Floating;
  4157. if (T->isAnyComplexType())
  4158. return AVK_Complex;
  4159. llvm_unreachable("Type not integer, floating, or complex");
  4160. }
  4161. // Changes the absolute value function to a different type. Preserves whether
  4162. // the function is a builtin.
  4163. static unsigned changeAbsFunction(unsigned AbsKind,
  4164. AbsoluteValueKind ValueKind) {
  4165. switch (ValueKind) {
  4166. case AVK_Integer:
  4167. switch (AbsKind) {
  4168. default:
  4169. return 0;
  4170. case Builtin::BI__builtin_fabsf:
  4171. case Builtin::BI__builtin_fabs:
  4172. case Builtin::BI__builtin_fabsl:
  4173. case Builtin::BI__builtin_cabsf:
  4174. case Builtin::BI__builtin_cabs:
  4175. case Builtin::BI__builtin_cabsl:
  4176. return Builtin::BI__builtin_abs;
  4177. case Builtin::BIfabsf:
  4178. case Builtin::BIfabs:
  4179. case Builtin::BIfabsl:
  4180. case Builtin::BIcabsf:
  4181. case Builtin::BIcabs:
  4182. case Builtin::BIcabsl:
  4183. return Builtin::BIabs;
  4184. }
  4185. case AVK_Floating:
  4186. switch (AbsKind) {
  4187. default:
  4188. return 0;
  4189. case Builtin::BI__builtin_abs:
  4190. case Builtin::BI__builtin_labs:
  4191. case Builtin::BI__builtin_llabs:
  4192. case Builtin::BI__builtin_cabsf:
  4193. case Builtin::BI__builtin_cabs:
  4194. case Builtin::BI__builtin_cabsl:
  4195. return Builtin::BI__builtin_fabsf;
  4196. case Builtin::BIabs:
  4197. case Builtin::BIlabs:
  4198. case Builtin::BIllabs:
  4199. case Builtin::BIcabsf:
  4200. case Builtin::BIcabs:
  4201. case Builtin::BIcabsl:
  4202. return Builtin::BIfabsf;
  4203. }
  4204. case AVK_Complex:
  4205. switch (AbsKind) {
  4206. default:
  4207. return 0;
  4208. case Builtin::BI__builtin_abs:
  4209. case Builtin::BI__builtin_labs:
  4210. case Builtin::BI__builtin_llabs:
  4211. case Builtin::BI__builtin_fabsf:
  4212. case Builtin::BI__builtin_fabs:
  4213. case Builtin::BI__builtin_fabsl:
  4214. return Builtin::BI__builtin_cabsf;
  4215. case Builtin::BIabs:
  4216. case Builtin::BIlabs:
  4217. case Builtin::BIllabs:
  4218. case Builtin::BIfabsf:
  4219. case Builtin::BIfabs:
  4220. case Builtin::BIfabsl:
  4221. return Builtin::BIcabsf;
  4222. }
  4223. }
  4224. llvm_unreachable("Unable to convert function");
  4225. }
  4226. static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
  4227. const IdentifierInfo *FnInfo = FDecl->getIdentifier();
  4228. if (!FnInfo)
  4229. return 0;
  4230. switch (FDecl->getBuiltinID()) {
  4231. default:
  4232. return 0;
  4233. case Builtin::BI__builtin_abs:
  4234. case Builtin::BI__builtin_fabs:
  4235. case Builtin::BI__builtin_fabsf:
  4236. case Builtin::BI__builtin_fabsl:
  4237. case Builtin::BI__builtin_labs:
  4238. case Builtin::BI__builtin_llabs:
  4239. case Builtin::BI__builtin_cabs:
  4240. case Builtin::BI__builtin_cabsf:
  4241. case Builtin::BI__builtin_cabsl:
  4242. case Builtin::BIabs:
  4243. case Builtin::BIlabs:
  4244. case Builtin::BIllabs:
  4245. case Builtin::BIfabs:
  4246. case Builtin::BIfabsf:
  4247. case Builtin::BIfabsl:
  4248. case Builtin::BIcabs:
  4249. case Builtin::BIcabsf:
  4250. case Builtin::BIcabsl:
  4251. return FDecl->getBuiltinID();
  4252. }
  4253. llvm_unreachable("Unknown Builtin type");
  4254. }
  4255. // If the replacement is valid, emit a note with replacement function.
  4256. // Additionally, suggest including the proper header if not already included.
  4257. static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
  4258. unsigned AbsKind, QualType ArgType) {
  4259. bool EmitHeaderHint = true;
  4260. const char *HeaderName = nullptr;
  4261. const char *FunctionName = nullptr;
  4262. if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
  4263. FunctionName = "std::abs";
  4264. if (ArgType->isIntegralOrEnumerationType()) {
  4265. HeaderName = "cstdlib";
  4266. } else if (ArgType->isRealFloatingType()) {
  4267. HeaderName = "cmath";
  4268. } else {
  4269. llvm_unreachable("Invalid Type");
  4270. }
  4271. // Lookup all std::abs
  4272. if (NamespaceDecl *Std = S.getStdNamespace()) {
  4273. LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
  4274. R.suppressDiagnostics();
  4275. S.LookupQualifiedName(R, Std);
  4276. for (const auto *I : R) {
  4277. const FunctionDecl *FDecl = nullptr;
  4278. if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
  4279. FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
  4280. } else {
  4281. FDecl = dyn_cast<FunctionDecl>(I);
  4282. }
  4283. if (!FDecl)
  4284. continue;
  4285. // Found std::abs(), check that they are the right ones.
  4286. if (FDecl->getNumParams() != 1)
  4287. continue;
  4288. // Check that the parameter type can handle the argument.
  4289. QualType ParamType = FDecl->getParamDecl(0)->getType();
  4290. if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
  4291. S.Context.getTypeSize(ArgType) <=
  4292. S.Context.getTypeSize(ParamType)) {
  4293. // Found a function, don't need the header hint.
  4294. EmitHeaderHint = false;
  4295. break;
  4296. }
  4297. }
  4298. }
  4299. } else {
  4300. FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
  4301. HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
  4302. if (HeaderName) {
  4303. DeclarationName DN(&S.Context.Idents.get(FunctionName));
  4304. LookupResult R(S, DN, Loc, Sema::LookupAnyName);
  4305. R.suppressDiagnostics();
  4306. S.LookupName(R, S.getCurScope());
  4307. if (R.isSingleResult()) {
  4308. FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
  4309. if (FD && FD->getBuiltinID() == AbsKind) {
  4310. EmitHeaderHint = false;
  4311. } else {
  4312. return;
  4313. }
  4314. } else if (!R.empty()) {
  4315. return;
  4316. }
  4317. }
  4318. }
  4319. S.Diag(Loc, diag::note_replace_abs_function)
  4320. << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
  4321. if (!HeaderName)
  4322. return;
  4323. if (!EmitHeaderHint)
  4324. return;
  4325. S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
  4326. << FunctionName;
  4327. }
  4328. static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
  4329. if (!FDecl)
  4330. return false;
  4331. if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
  4332. return false;
  4333. const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
  4334. while (ND && ND->isInlineNamespace()) {
  4335. ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
  4336. }
  4337. if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
  4338. return false;
  4339. if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
  4340. return false;
  4341. return true;
  4342. }
  4343. // Warn when using the wrong abs() function.
  4344. void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
  4345. const FunctionDecl *FDecl,
  4346. IdentifierInfo *FnInfo) {
  4347. if (Call->getNumArgs() != 1)
  4348. return;
  4349. unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
  4350. bool IsStdAbs = IsFunctionStdAbs(FDecl);
  4351. if (AbsKind == 0 && !IsStdAbs)
  4352. return;
  4353. QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
  4354. QualType ParamType = Call->getArg(0)->getType();
  4355. // Unsigned types cannot be negative. Suggest removing the absolute value
  4356. // function call.
  4357. if (ArgType->isUnsignedIntegerType()) {
  4358. const char *FunctionName =
  4359. IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
  4360. Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
  4361. Diag(Call->getExprLoc(), diag::note_remove_abs)
  4362. << FunctionName
  4363. << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
  4364. return;
  4365. }
  4366. // std::abs has overloads which prevent most of the absolute value problems
  4367. // from occurring.
  4368. if (IsStdAbs)
  4369. return;
  4370. AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
  4371. AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
  4372. // The argument and parameter are the same kind. Check if they are the right
  4373. // size.
  4374. if (ArgValueKind == ParamValueKind) {
  4375. if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
  4376. return;
  4377. unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
  4378. Diag(Call->getExprLoc(), diag::warn_abs_too_small)
  4379. << FDecl << ArgType << ParamType;
  4380. if (NewAbsKind == 0)
  4381. return;
  4382. emitReplacement(*this, Call->getExprLoc(),
  4383. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  4384. return;
  4385. }
  4386. // ArgValueKind != ParamValueKind
  4387. // The wrong type of absolute value function was used. Attempt to find the
  4388. // proper one.
  4389. unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
  4390. NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
  4391. if (NewAbsKind == 0)
  4392. return;
  4393. Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
  4394. << FDecl << ParamValueKind << ArgValueKind;
  4395. emitReplacement(*this, Call->getExprLoc(),
  4396. Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
  4397. return;
  4398. }
  4399. //===--- CHECK: Standard memory functions ---------------------------------===//
  4400. /// \brief Takes the expression passed to the size_t parameter of functions
  4401. /// such as memcmp, strncat, etc and warns if it's a comparison.
  4402. ///
  4403. /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
  4404. static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
  4405. IdentifierInfo *FnName,
  4406. SourceLocation FnLoc,
  4407. SourceLocation RParenLoc) {
  4408. const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
  4409. if (!Size)
  4410. return false;
  4411. // if E is binop and op is >, <, >=, <=, ==, &&, ||:
  4412. if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
  4413. return false;
  4414. SourceRange SizeRange = Size->getSourceRange();
  4415. S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
  4416. << SizeRange << FnName;
  4417. S.Diag(FnLoc, diag::note_memsize_comparison_paren)
  4418. << FnName << FixItHint::CreateInsertion(
  4419. S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
  4420. << FixItHint::CreateRemoval(RParenLoc);
  4421. S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
  4422. << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
  4423. << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
  4424. ")");
  4425. return true;
  4426. }
  4427. /// \brief Determine whether the given type is or contains a dynamic class type
  4428. /// (e.g., whether it has a vtable).
  4429. static const CXXRecordDecl *getContainedDynamicClass(QualType T,
  4430. bool &IsContained) {
  4431. // Look through array types while ignoring qualifiers.
  4432. const Type *Ty = T->getBaseElementTypeUnsafe();
  4433. IsContained = false;
  4434. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  4435. RD = RD ? RD->getDefinition() : nullptr;
  4436. if (!RD)
  4437. return nullptr;
  4438. if (RD->isDynamicClass())
  4439. return RD;
  4440. // Check all the fields. If any bases were dynamic, the class is dynamic.
  4441. // It's impossible for a class to transitively contain itself by value, so
  4442. // infinite recursion is impossible.
  4443. for (auto *FD : RD->fields()) {
  4444. bool SubContained;
  4445. if (const CXXRecordDecl *ContainedRD =
  4446. getContainedDynamicClass(FD->getType(), SubContained)) {
  4447. IsContained = true;
  4448. return ContainedRD;
  4449. }
  4450. }
  4451. return nullptr;
  4452. }
  4453. /// \brief If E is a sizeof expression, returns its argument expression,
  4454. /// otherwise returns NULL.
  4455. static const Expr *getSizeOfExprArg(const Expr *E) {
  4456. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  4457. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  4458. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  4459. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  4460. return nullptr;
  4461. }
  4462. /// \brief If E is a sizeof expression, returns its argument type.
  4463. static QualType getSizeOfArgType(const Expr *E) {
  4464. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  4465. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  4466. if (SizeOf->getKind() == clang::UETT_SizeOf)
  4467. return SizeOf->getTypeOfArgument();
  4468. return QualType();
  4469. }
  4470. /// \brief Check for dangerous or invalid arguments to memset().
  4471. ///
  4472. /// This issues warnings on known problematic, dangerous or unspecified
  4473. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  4474. /// function calls.
  4475. ///
  4476. /// \param Call The call expression to diagnose.
  4477. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  4478. unsigned BId,
  4479. IdentifierInfo *FnName) {
  4480. assert(BId != 0);
  4481. // It is possible to have a non-standard definition of memset. Validate
  4482. // we have enough arguments, and if not, abort further checking.
  4483. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  4484. if (Call->getNumArgs() < ExpectedNumArgs)
  4485. return;
  4486. unsigned LastArg = (BId == Builtin::BImemset ||
  4487. BId == Builtin::BIstrndup ? 1 : 2);
  4488. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  4489. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  4490. if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
  4491. Call->getLocStart(), Call->getRParenLoc()))
  4492. return;
  4493. // We have special checking when the length is a sizeof expression.
  4494. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  4495. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  4496. llvm::FoldingSetNodeID SizeOfArgID;
  4497. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  4498. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  4499. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  4500. QualType DestTy = Dest->getType();
  4501. QualType PointeeTy;
  4502. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  4503. PointeeTy = DestPtrTy->getPointeeType();
  4504. // Never warn about void type pointers. This can be used to suppress
  4505. // false positives.
  4506. if (PointeeTy->isVoidType())
  4507. continue;
  4508. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  4509. // actually comparing the expressions for equality. Because computing the
  4510. // expression IDs can be expensive, we only do this if the diagnostic is
  4511. // enabled.
  4512. if (SizeOfArg &&
  4513. !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
  4514. SizeOfArg->getExprLoc())) {
  4515. // We only compute IDs for expressions if the warning is enabled, and
  4516. // cache the sizeof arg's ID.
  4517. if (SizeOfArgID == llvm::FoldingSetNodeID())
  4518. SizeOfArg->Profile(SizeOfArgID, Context, true);
  4519. llvm::FoldingSetNodeID DestID;
  4520. Dest->Profile(DestID, Context, true);
  4521. if (DestID == SizeOfArgID) {
  4522. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  4523. // over sizeof(src) as well.
  4524. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  4525. StringRef ReadableName = FnName->getName();
  4526. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  4527. if (UnaryOp->getOpcode() == UO_AddrOf)
  4528. ActionIdx = 1; // If its an address-of operator, just remove it.
  4529. if (!PointeeTy->isIncompleteType() &&
  4530. (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
  4531. ActionIdx = 2; // If the pointee's size is sizeof(char),
  4532. // suggest an explicit length.
  4533. // If the function is defined as a builtin macro, do not show macro
  4534. // expansion.
  4535. SourceLocation SL = SizeOfArg->getExprLoc();
  4536. SourceRange DSR = Dest->getSourceRange();
  4537. SourceRange SSR = SizeOfArg->getSourceRange();
  4538. SourceManager &SM = getSourceManager();
  4539. if (SM.isMacroArgExpansion(SL)) {
  4540. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  4541. SL = SM.getSpellingLoc(SL);
  4542. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  4543. SM.getSpellingLoc(DSR.getEnd()));
  4544. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  4545. SM.getSpellingLoc(SSR.getEnd()));
  4546. }
  4547. DiagRuntimeBehavior(SL, SizeOfArg,
  4548. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  4549. << ReadableName
  4550. << PointeeTy
  4551. << DestTy
  4552. << DSR
  4553. << SSR);
  4554. DiagRuntimeBehavior(SL, SizeOfArg,
  4555. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  4556. << ActionIdx
  4557. << SSR);
  4558. break;
  4559. }
  4560. }
  4561. // Also check for cases where the sizeof argument is the exact same
  4562. // type as the memory argument, and where it points to a user-defined
  4563. // record type.
  4564. if (SizeOfArgTy != QualType()) {
  4565. if (PointeeTy->isRecordType() &&
  4566. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  4567. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  4568. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  4569. << FnName << SizeOfArgTy << ArgIdx
  4570. << PointeeTy << Dest->getSourceRange()
  4571. << LenExpr->getSourceRange());
  4572. break;
  4573. }
  4574. }
  4575. } else if (DestTy->isArrayType()) {
  4576. PointeeTy = DestTy;
  4577. }
  4578. if (PointeeTy == QualType())
  4579. continue;
  4580. // Always complain about dynamic classes.
  4581. bool IsContained;
  4582. if (const CXXRecordDecl *ContainedRD =
  4583. getContainedDynamicClass(PointeeTy, IsContained)) {
  4584. unsigned OperationType = 0;
  4585. // "overwritten" if we're warning about the destination for any call
  4586. // but memcmp; otherwise a verb appropriate to the call.
  4587. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  4588. if (BId == Builtin::BImemcpy)
  4589. OperationType = 1;
  4590. else if(BId == Builtin::BImemmove)
  4591. OperationType = 2;
  4592. else if (BId == Builtin::BImemcmp)
  4593. OperationType = 3;
  4594. }
  4595. DiagRuntimeBehavior(
  4596. Dest->getExprLoc(), Dest,
  4597. PDiag(diag::warn_dyn_class_memaccess)
  4598. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  4599. << FnName << IsContained << ContainedRD << OperationType
  4600. << Call->getCallee()->getSourceRange());
  4601. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  4602. BId != Builtin::BImemset)
  4603. DiagRuntimeBehavior(
  4604. Dest->getExprLoc(), Dest,
  4605. PDiag(diag::warn_arc_object_memaccess)
  4606. << ArgIdx << FnName << PointeeTy
  4607. << Call->getCallee()->getSourceRange());
  4608. else
  4609. continue;
  4610. DiagRuntimeBehavior(
  4611. Dest->getExprLoc(), Dest,
  4612. PDiag(diag::note_bad_memaccess_silence)
  4613. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  4614. break;
  4615. }
  4616. }
  4617. // A little helper routine: ignore addition and subtraction of integer literals.
  4618. // This intentionally does not ignore all integer constant expressions because
  4619. // we don't want to remove sizeof().
  4620. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  4621. Ex = Ex->IgnoreParenCasts();
  4622. for (;;) {
  4623. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  4624. if (!BO || !BO->isAdditiveOp())
  4625. break;
  4626. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  4627. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  4628. if (isa<IntegerLiteral>(RHS))
  4629. Ex = LHS;
  4630. else if (isa<IntegerLiteral>(LHS))
  4631. Ex = RHS;
  4632. else
  4633. break;
  4634. }
  4635. return Ex;
  4636. }
  4637. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  4638. ASTContext &Context) {
  4639. // Only handle constant-sized or VLAs, but not flexible members.
  4640. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  4641. // Only issue the FIXIT for arrays of size > 1.
  4642. if (CAT->getSize().getSExtValue() <= 1)
  4643. return false;
  4644. } else if (!Ty->isVariableArrayType()) {
  4645. return false;
  4646. }
  4647. return true;
  4648. }
  4649. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  4650. // be the size of the source, instead of the destination.
  4651. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  4652. IdentifierInfo *FnName) {
  4653. // Don't crash if the user has the wrong number of arguments
  4654. unsigned NumArgs = Call->getNumArgs();
  4655. if ((NumArgs != 3) && (NumArgs != 4))
  4656. return;
  4657. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  4658. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  4659. const Expr *CompareWithSrc = nullptr;
  4660. if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
  4661. Call->getLocStart(), Call->getRParenLoc()))
  4662. return;
  4663. // Look for 'strlcpy(dst, x, sizeof(x))'
  4664. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  4665. CompareWithSrc = Ex;
  4666. else {
  4667. // Look for 'strlcpy(dst, x, strlen(x))'
  4668. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  4669. if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
  4670. SizeCall->getNumArgs() == 1)
  4671. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  4672. }
  4673. }
  4674. if (!CompareWithSrc)
  4675. return;
  4676. // Determine if the argument to sizeof/strlen is equal to the source
  4677. // argument. In principle there's all kinds of things you could do
  4678. // here, for instance creating an == expression and evaluating it with
  4679. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  4680. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  4681. if (!SrcArgDRE)
  4682. return;
  4683. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  4684. if (!CompareWithSrcDRE ||
  4685. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  4686. return;
  4687. const Expr *OriginalSizeArg = Call->getArg(2);
  4688. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  4689. << OriginalSizeArg->getSourceRange() << FnName;
  4690. // Output a FIXIT hint if the destination is an array (rather than a
  4691. // pointer to an array). This could be enhanced to handle some
  4692. // pointers if we know the actual size, like if DstArg is 'array+2'
  4693. // we could say 'sizeof(array)-2'.
  4694. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  4695. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  4696. return;
  4697. SmallString<128> sizeString;
  4698. llvm::raw_svector_ostream OS(sizeString);
  4699. OS << "sizeof(";
  4700. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4701. OS << ")";
  4702. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  4703. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  4704. OS.str());
  4705. }
  4706. /// Check if two expressions refer to the same declaration.
  4707. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  4708. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  4709. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  4710. return D1->getDecl() == D2->getDecl();
  4711. return false;
  4712. }
  4713. static const Expr *getStrlenExprArg(const Expr *E) {
  4714. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  4715. const FunctionDecl *FD = CE->getDirectCallee();
  4716. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  4717. return nullptr;
  4718. return CE->getArg(0)->IgnoreParenCasts();
  4719. }
  4720. return nullptr;
  4721. }
  4722. // Warn on anti-patterns as the 'size' argument to strncat.
  4723. // The correct size argument should look like following:
  4724. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  4725. void Sema::CheckStrncatArguments(const CallExpr *CE,
  4726. IdentifierInfo *FnName) {
  4727. // Don't crash if the user has the wrong number of arguments.
  4728. if (CE->getNumArgs() < 3)
  4729. return;
  4730. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  4731. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  4732. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  4733. if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
  4734. CE->getRParenLoc()))
  4735. return;
  4736. // Identify common expressions, which are wrongly used as the size argument
  4737. // to strncat and may lead to buffer overflows.
  4738. unsigned PatternType = 0;
  4739. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  4740. // - sizeof(dst)
  4741. if (referToTheSameDecl(SizeOfArg, DstArg))
  4742. PatternType = 1;
  4743. // - sizeof(src)
  4744. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  4745. PatternType = 2;
  4746. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  4747. if (BE->getOpcode() == BO_Sub) {
  4748. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  4749. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  4750. // - sizeof(dst) - strlen(dst)
  4751. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  4752. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  4753. PatternType = 1;
  4754. // - sizeof(src) - (anything)
  4755. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  4756. PatternType = 2;
  4757. }
  4758. }
  4759. if (PatternType == 0)
  4760. return;
  4761. // Generate the diagnostic.
  4762. SourceLocation SL = LenArg->getLocStart();
  4763. SourceRange SR = LenArg->getSourceRange();
  4764. SourceManager &SM = getSourceManager();
  4765. // If the function is defined as a builtin macro, do not show macro expansion.
  4766. if (SM.isMacroArgExpansion(SL)) {
  4767. SL = SM.getSpellingLoc(SL);
  4768. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  4769. SM.getSpellingLoc(SR.getEnd()));
  4770. }
  4771. // Check if the destination is an array (rather than a pointer to an array).
  4772. QualType DstTy = DstArg->getType();
  4773. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  4774. Context);
  4775. if (!isKnownSizeArray) {
  4776. if (PatternType == 1)
  4777. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  4778. else
  4779. Diag(SL, diag::warn_strncat_src_size) << SR;
  4780. return;
  4781. }
  4782. if (PatternType == 1)
  4783. Diag(SL, diag::warn_strncat_large_size) << SR;
  4784. else
  4785. Diag(SL, diag::warn_strncat_src_size) << SR;
  4786. SmallString<128> sizeString;
  4787. llvm::raw_svector_ostream OS(sizeString);
  4788. OS << "sizeof(";
  4789. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4790. OS << ") - ";
  4791. OS << "strlen(";
  4792. DstArg->printPretty(OS, nullptr, getPrintingPolicy());
  4793. OS << ") - 1";
  4794. Diag(SL, diag::note_strncat_wrong_size)
  4795. << FixItHint::CreateReplacement(SR, OS.str());
  4796. }
  4797. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  4798. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4799. Decl *ParentDecl);
  4800. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4801. Decl *ParentDecl);
  4802. /// CheckReturnStackAddr - Check if a return statement returns the address
  4803. /// of a stack variable.
  4804. static void
  4805. CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
  4806. SourceLocation ReturnLoc) {
  4807. Expr *stackE = nullptr;
  4808. SmallVector<DeclRefExpr *, 8> refVars;
  4809. // Perform checking for returned stack addresses, local blocks,
  4810. // label addresses or references to temporaries.
  4811. if (lhsType->isPointerType() ||
  4812. (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  4813. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
  4814. } else if (lhsType->isReferenceType()) {
  4815. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
  4816. }
  4817. if (!stackE)
  4818. return; // Nothing suspicious was found.
  4819. SourceLocation diagLoc;
  4820. SourceRange diagRange;
  4821. if (refVars.empty()) {
  4822. diagLoc = stackE->getLocStart();
  4823. diagRange = stackE->getSourceRange();
  4824. } else {
  4825. // We followed through a reference variable. 'stackE' contains the
  4826. // problematic expression but we will warn at the return statement pointing
  4827. // at the reference variable. We will later display the "trail" of
  4828. // reference variables using notes.
  4829. diagLoc = refVars[0]->getLocStart();
  4830. diagRange = refVars[0]->getSourceRange();
  4831. }
  4832. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  4833. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  4834. : diag::warn_ret_stack_addr)
  4835. << DR->getDecl()->getDeclName() << diagRange;
  4836. } else if (isa<BlockExpr>(stackE)) { // local block.
  4837. S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  4838. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  4839. S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  4840. } else { // local temporary.
  4841. S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  4842. : diag::warn_ret_local_temp_addr)
  4843. << diagRange;
  4844. }
  4845. // Display the "trail" of reference variables that we followed until we
  4846. // found the problematic expression using notes.
  4847. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  4848. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  4849. // If this var binds to another reference var, show the range of the next
  4850. // var, otherwise the var binds to the problematic expression, in which case
  4851. // show the range of the expression.
  4852. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  4853. : stackE->getSourceRange();
  4854. S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  4855. << VD->getDeclName() << range;
  4856. }
  4857. }
  4858. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  4859. /// check if the expression in a return statement evaluates to an address
  4860. /// to a location on the stack, a local block, an address of a label, or a
  4861. /// reference to local temporary. The recursion is used to traverse the
  4862. /// AST of the return expression, with recursion backtracking when we
  4863. /// encounter a subexpression that (1) clearly does not lead to one of the
  4864. /// above problematic expressions (2) is something we cannot determine leads to
  4865. /// a problematic expression based on such local checking.
  4866. ///
  4867. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  4868. /// the expression that they point to. Such variables are added to the
  4869. /// 'refVars' vector so that we know what the reference variable "trail" was.
  4870. ///
  4871. /// EvalAddr processes expressions that are pointers that are used as
  4872. /// references (and not L-values). EvalVal handles all other values.
  4873. /// At the base case of the recursion is a check for the above problematic
  4874. /// expressions.
  4875. ///
  4876. /// This implementation handles:
  4877. ///
  4878. /// * pointer-to-pointer casts
  4879. /// * implicit conversions from array references to pointers
  4880. /// * taking the address of fields
  4881. /// * arbitrary interplay between "&" and "*" operators
  4882. /// * pointer arithmetic from an address of a stack variable
  4883. /// * taking the address of an array element where the array is on the stack
  4884. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  4885. Decl *ParentDecl) {
  4886. if (E->isTypeDependent())
  4887. return nullptr;
  4888. // We should only be called for evaluating pointer expressions.
  4889. assert((E->getType()->isAnyPointerType() ||
  4890. E->getType()->isBlockPointerType() ||
  4891. E->getType()->isObjCQualifiedIdType()) &&
  4892. "EvalAddr only works on pointers");
  4893. E = E->IgnoreParens();
  4894. // Our "symbolic interpreter" is just a dispatch off the currently
  4895. // viewed AST node. We then recursively traverse the AST by calling
  4896. // EvalAddr and EvalVal appropriately.
  4897. switch (E->getStmtClass()) {
  4898. case Stmt::DeclRefExprClass: {
  4899. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  4900. // If we leave the immediate function, the lifetime isn't about to end.
  4901. if (DR->refersToEnclosingVariableOrCapture())
  4902. return nullptr;
  4903. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  4904. // If this is a reference variable, follow through to the expression that
  4905. // it points to.
  4906. if (V->hasLocalStorage() &&
  4907. V->getType()->isReferenceType() && V->hasInit()) {
  4908. // Add the reference variable to the "trail".
  4909. refVars.push_back(DR);
  4910. return EvalAddr(V->getInit(), refVars, ParentDecl);
  4911. }
  4912. return nullptr;
  4913. }
  4914. case Stmt::UnaryOperatorClass: {
  4915. // The only unary operator that make sense to handle here
  4916. // is AddrOf. All others don't make sense as pointers.
  4917. UnaryOperator *U = cast<UnaryOperator>(E);
  4918. if (U->getOpcode() == UO_AddrOf)
  4919. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  4920. else
  4921. return nullptr;
  4922. }
  4923. case Stmt::BinaryOperatorClass: {
  4924. // Handle pointer arithmetic. All other binary operators are not valid
  4925. // in this context.
  4926. BinaryOperator *B = cast<BinaryOperator>(E);
  4927. BinaryOperatorKind op = B->getOpcode();
  4928. if (op != BO_Add && op != BO_Sub)
  4929. return nullptr;
  4930. Expr *Base = B->getLHS();
  4931. // Determine which argument is the real pointer base. It could be
  4932. // the RHS argument instead of the LHS.
  4933. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  4934. assert (Base->getType()->isPointerType());
  4935. return EvalAddr(Base, refVars, ParentDecl);
  4936. }
  4937. // For conditional operators we need to see if either the LHS or RHS are
  4938. // valid DeclRefExpr*s. If one of them is valid, we return it.
  4939. case Stmt::ConditionalOperatorClass: {
  4940. ConditionalOperator *C = cast<ConditionalOperator>(E);
  4941. // Handle the GNU extension for missing LHS.
  4942. // FIXME: That isn't a ConditionalOperator, so doesn't get here.
  4943. if (Expr *LHSExpr = C->getLHS()) {
  4944. // In C++, we can have a throw-expression, which has 'void' type.
  4945. if (!LHSExpr->getType()->isVoidType())
  4946. if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
  4947. return LHS;
  4948. }
  4949. // In C++, we can have a throw-expression, which has 'void' type.
  4950. if (C->getRHS()->getType()->isVoidType())
  4951. return nullptr;
  4952. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  4953. }
  4954. case Stmt::BlockExprClass:
  4955. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  4956. return E; // local block.
  4957. return nullptr;
  4958. case Stmt::AddrLabelExprClass:
  4959. return E; // address of label.
  4960. case Stmt::ExprWithCleanupsClass:
  4961. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  4962. ParentDecl);
  4963. // For casts, we need to handle conversions from arrays to
  4964. // pointer values, and pointer-to-pointer conversions.
  4965. case Stmt::ImplicitCastExprClass:
  4966. case Stmt::CStyleCastExprClass:
  4967. case Stmt::CXXFunctionalCastExprClass:
  4968. case Stmt::ObjCBridgedCastExprClass:
  4969. case Stmt::CXXStaticCastExprClass:
  4970. case Stmt::CXXDynamicCastExprClass:
  4971. case Stmt::CXXConstCastExprClass:
  4972. case Stmt::CXXReinterpretCastExprClass: {
  4973. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  4974. switch (cast<CastExpr>(E)->getCastKind()) {
  4975. case CK_LValueToRValue:
  4976. case CK_NoOp:
  4977. case CK_BaseToDerived:
  4978. case CK_DerivedToBase:
  4979. case CK_UncheckedDerivedToBase:
  4980. case CK_Dynamic:
  4981. case CK_CPointerToObjCPointerCast:
  4982. case CK_BlockPointerToObjCPointerCast:
  4983. case CK_AnyPointerToBlockPointerCast:
  4984. return EvalAddr(SubExpr, refVars, ParentDecl);
  4985. case CK_ArrayToPointerDecay:
  4986. return EvalVal(SubExpr, refVars, ParentDecl);
  4987. case CK_BitCast:
  4988. if (SubExpr->getType()->isAnyPointerType() ||
  4989. SubExpr->getType()->isBlockPointerType() ||
  4990. SubExpr->getType()->isObjCQualifiedIdType())
  4991. return EvalAddr(SubExpr, refVars, ParentDecl);
  4992. else
  4993. return nullptr;
  4994. default:
  4995. return nullptr;
  4996. }
  4997. }
  4998. case Stmt::MaterializeTemporaryExprClass:
  4999. if (Expr *Result = EvalAddr(
  5000. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  5001. refVars, ParentDecl))
  5002. return Result;
  5003. return E;
  5004. // Everything else: we simply don't reason about them.
  5005. default:
  5006. return nullptr;
  5007. }
  5008. }
  5009. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  5010. /// See the comments for EvalAddr for more details.
  5011. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  5012. Decl *ParentDecl) {
  5013. do {
  5014. // We should only be called for evaluating non-pointer expressions, or
  5015. // expressions with a pointer type that are not used as references but instead
  5016. // are l-values (e.g., DeclRefExpr with a pointer type).
  5017. // Our "symbolic interpreter" is just a dispatch off the currently
  5018. // viewed AST node. We then recursively traverse the AST by calling
  5019. // EvalAddr and EvalVal appropriately.
  5020. E = E->IgnoreParens();
  5021. switch (E->getStmtClass()) {
  5022. case Stmt::ImplicitCastExprClass: {
  5023. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  5024. if (IE->getValueKind() == VK_LValue) {
  5025. E = IE->getSubExpr();
  5026. continue;
  5027. }
  5028. return nullptr;
  5029. }
  5030. case Stmt::ExprWithCleanupsClass:
  5031. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  5032. case Stmt::DeclRefExprClass: {
  5033. // When we hit a DeclRefExpr we are looking at code that refers to a
  5034. // variable's name. If it's not a reference variable we check if it has
  5035. // local storage within the function, and if so, return the expression.
  5036. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  5037. // If we leave the immediate function, the lifetime isn't about to end.
  5038. if (DR->refersToEnclosingVariableOrCapture())
  5039. return nullptr;
  5040. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  5041. // Check if it refers to itself, e.g. "int& i = i;".
  5042. if (V == ParentDecl)
  5043. return DR;
  5044. if (V->hasLocalStorage()) {
  5045. if (!V->getType()->isReferenceType())
  5046. return DR;
  5047. // Reference variable, follow through to the expression that
  5048. // it points to.
  5049. if (V->hasInit()) {
  5050. // Add the reference variable to the "trail".
  5051. refVars.push_back(DR);
  5052. return EvalVal(V->getInit(), refVars, V);
  5053. }
  5054. }
  5055. }
  5056. return nullptr;
  5057. }
  5058. case Stmt::UnaryOperatorClass: {
  5059. // The only unary operator that make sense to handle here
  5060. // is Deref. All others don't resolve to a "name." This includes
  5061. // handling all sorts of rvalues passed to a unary operator.
  5062. UnaryOperator *U = cast<UnaryOperator>(E);
  5063. if (U->getOpcode() == UO_Deref)
  5064. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  5065. return nullptr;
  5066. }
  5067. case Stmt::ArraySubscriptExprClass: {
  5068. // Array subscripts are potential references to data on the stack. We
  5069. // retrieve the DeclRefExpr* for the array variable if it indeed
  5070. // has local storage.
  5071. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  5072. }
  5073. case Stmt::ConditionalOperatorClass: {
  5074. // For conditional operators we need to see if either the LHS or RHS are
  5075. // non-NULL Expr's. If one is non-NULL, we return it.
  5076. ConditionalOperator *C = cast<ConditionalOperator>(E);
  5077. // Handle the GNU extension for missing LHS.
  5078. if (Expr *LHSExpr = C->getLHS()) {
  5079. // In C++, we can have a throw-expression, which has 'void' type.
  5080. if (!LHSExpr->getType()->isVoidType())
  5081. if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
  5082. return LHS;
  5083. }
  5084. // In C++, we can have a throw-expression, which has 'void' type.
  5085. if (C->getRHS()->getType()->isVoidType())
  5086. return nullptr;
  5087. return EvalVal(C->getRHS(), refVars, ParentDecl);
  5088. }
  5089. // Accesses to members are potential references to data on the stack.
  5090. case Stmt::MemberExprClass: {
  5091. MemberExpr *M = cast<MemberExpr>(E);
  5092. // Check for indirect access. We only want direct field accesses.
  5093. if (M->isArrow())
  5094. return nullptr;
  5095. // Check whether the member type is itself a reference, in which case
  5096. // we're not going to refer to the member, but to what the member refers to.
  5097. if (M->getMemberDecl()->getType()->isReferenceType())
  5098. return nullptr;
  5099. return EvalVal(M->getBase(), refVars, ParentDecl);
  5100. }
  5101. case Stmt::MaterializeTemporaryExprClass:
  5102. if (Expr *Result = EvalVal(
  5103. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  5104. refVars, ParentDecl))
  5105. return Result;
  5106. return E;
  5107. default:
  5108. // Check that we don't return or take the address of a reference to a
  5109. // temporary. This is only useful in C++.
  5110. if (!E->isTypeDependent() && E->isRValue())
  5111. return E;
  5112. // Everything else: we simply don't reason about them.
  5113. return nullptr;
  5114. }
  5115. } while (true);
  5116. }
  5117. void
  5118. Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
  5119. SourceLocation ReturnLoc,
  5120. bool isObjCMethod,
  5121. const AttrVec *Attrs,
  5122. const FunctionDecl *FD) {
  5123. CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
  5124. // Check if the return value is null but should not be.
  5125. if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
  5126. (!isObjCMethod && isNonNullType(Context, lhsType))) &&
  5127. CheckNonNullExpr(*this, RetValExp))
  5128. Diag(ReturnLoc, diag::warn_null_ret)
  5129. << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
  5130. // C++11 [basic.stc.dynamic.allocation]p4:
  5131. // If an allocation function declared with a non-throwing
  5132. // exception-specification fails to allocate storage, it shall return
  5133. // a null pointer. Any other allocation function that fails to allocate
  5134. // storage shall indicate failure only by throwing an exception [...]
  5135. if (FD) {
  5136. OverloadedOperatorKind Op = FD->getOverloadedOperator();
  5137. if (Op == OO_New || Op == OO_Array_New) {
  5138. const FunctionProtoType *Proto
  5139. = FD->getType()->castAs<FunctionProtoType>();
  5140. if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
  5141. CheckNonNullExpr(*this, RetValExp))
  5142. Diag(ReturnLoc, diag::warn_operator_new_returns_null)
  5143. << FD << getLangOpts().CPlusPlus11;
  5144. }
  5145. }
  5146. }
  5147. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  5148. /// Check for comparisons of floating point operands using != and ==.
  5149. /// Issue a warning if these are no self-comparisons, as they are not likely
  5150. /// to do what the programmer intended.
  5151. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  5152. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  5153. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  5154. // Special case: check for x == x (which is OK).
  5155. // Do not emit warnings for such cases.
  5156. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  5157. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  5158. if (DRL->getDecl() == DRR->getDecl())
  5159. return;
  5160. // Special case: check for comparisons against literals that can be exactly
  5161. // represented by APFloat. In such cases, do not emit a warning. This
  5162. // is a heuristic: often comparison against such literals are used to
  5163. // detect if a value in a variable has not changed. This clearly can
  5164. // lead to false negatives.
  5165. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  5166. if (FLL->isExact())
  5167. return;
  5168. } else
  5169. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  5170. if (FLR->isExact())
  5171. return;
  5172. // Check for comparisons with builtin types.
  5173. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  5174. if (CL->getBuiltinCallee())
  5175. return;
  5176. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  5177. if (CR->getBuiltinCallee())
  5178. return;
  5179. // Emit the diagnostic.
  5180. Diag(Loc, diag::warn_floatingpoint_eq)
  5181. << LHS->getSourceRange() << RHS->getSourceRange();
  5182. }
  5183. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  5184. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  5185. namespace {
  5186. /// Structure recording the 'active' range of an integer-valued
  5187. /// expression.
  5188. struct IntRange {
  5189. /// The number of bits active in the int.
  5190. unsigned Width;
  5191. /// True if the int is known not to have negative values.
  5192. bool NonNegative;
  5193. IntRange(unsigned Width, bool NonNegative)
  5194. : Width(Width), NonNegative(NonNegative)
  5195. {}
  5196. /// Returns the range of the bool type.
  5197. static IntRange forBoolType() {
  5198. return IntRange(1, true);
  5199. }
  5200. /// Returns the range of an opaque value of the given integral type.
  5201. static IntRange forValueOfType(ASTContext &C, QualType T) {
  5202. return forValueOfCanonicalType(C,
  5203. T->getCanonicalTypeInternal().getTypePtr());
  5204. }
  5205. /// Returns the range of an opaque value of a canonical integral type.
  5206. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  5207. assert(T->isCanonicalUnqualified());
  5208. if (const VectorType *VT = dyn_cast<VectorType>(T))
  5209. T = VT->getElementType().getTypePtr();
  5210. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  5211. T = CT->getElementType().getTypePtr();
  5212. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  5213. T = AT->getValueType().getTypePtr();
  5214. // For enum types, use the known bit width of the enumerators.
  5215. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  5216. EnumDecl *Enum = ET->getDecl();
  5217. if (!Enum->isCompleteDefinition())
  5218. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  5219. unsigned NumPositive = Enum->getNumPositiveBits();
  5220. unsigned NumNegative = Enum->getNumNegativeBits();
  5221. if (NumNegative == 0)
  5222. return IntRange(NumPositive, true/*NonNegative*/);
  5223. else
  5224. return IntRange(std::max(NumPositive + 1, NumNegative),
  5225. false/*NonNegative*/);
  5226. }
  5227. const BuiltinType *BT = cast<BuiltinType>(T);
  5228. assert(BT->isInteger());
  5229. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  5230. }
  5231. /// Returns the "target" range of a canonical integral type, i.e.
  5232. /// the range of values expressible in the type.
  5233. ///
  5234. /// This matches forValueOfCanonicalType except that enums have the
  5235. /// full range of their type, not the range of their enumerators.
  5236. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  5237. assert(T->isCanonicalUnqualified());
  5238. if (const VectorType *VT = dyn_cast<VectorType>(T))
  5239. T = VT->getElementType().getTypePtr();
  5240. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  5241. T = CT->getElementType().getTypePtr();
  5242. if (const AtomicType *AT = dyn_cast<AtomicType>(T))
  5243. T = AT->getValueType().getTypePtr();
  5244. if (const EnumType *ET = dyn_cast<EnumType>(T))
  5245. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  5246. const BuiltinType *BT = cast<BuiltinType>(T);
  5247. assert(BT->isInteger());
  5248. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  5249. }
  5250. /// Returns the supremum of two ranges: i.e. their conservative merge.
  5251. static IntRange join(IntRange L, IntRange R) {
  5252. return IntRange(std::max(L.Width, R.Width),
  5253. L.NonNegative && R.NonNegative);
  5254. }
  5255. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  5256. static IntRange meet(IntRange L, IntRange R) {
  5257. return IntRange(std::min(L.Width, R.Width),
  5258. L.NonNegative || R.NonNegative);
  5259. }
  5260. };
  5261. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  5262. unsigned MaxWidth) {
  5263. if (value.isSigned() && value.isNegative())
  5264. return IntRange(value.getMinSignedBits(), false);
  5265. if (value.getBitWidth() > MaxWidth)
  5266. value = value.trunc(MaxWidth);
  5267. // isNonNegative() just checks the sign bit without considering
  5268. // signedness.
  5269. return IntRange(value.getActiveBits(), true);
  5270. }
  5271. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  5272. unsigned MaxWidth) {
  5273. if (result.isInt())
  5274. return GetValueRange(C, result.getInt(), MaxWidth);
  5275. if (result.isVector()) {
  5276. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  5277. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  5278. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  5279. R = IntRange::join(R, El);
  5280. }
  5281. return R;
  5282. }
  5283. if (result.isComplexInt()) {
  5284. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  5285. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  5286. return IntRange::join(R, I);
  5287. }
  5288. // This can happen with lossless casts to intptr_t of "based" lvalues.
  5289. // Assume it might use arbitrary bits.
  5290. // FIXME: The only reason we need to pass the type in here is to get
  5291. // the sign right on this one case. It would be nice if APValue
  5292. // preserved this.
  5293. assert(result.isLValue() || result.isAddrLabelDiff());
  5294. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  5295. }
  5296. static QualType GetExprType(Expr *E) {
  5297. QualType Ty = E->getType();
  5298. if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
  5299. Ty = AtomicRHS->getValueType();
  5300. return Ty;
  5301. }
  5302. /// Pseudo-evaluate the given integer expression, estimating the
  5303. /// range of values it might take.
  5304. ///
  5305. /// \param MaxWidth - the width to which the value will be truncated
  5306. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  5307. E = E->IgnoreParens();
  5308. // Try a full evaluation first.
  5309. Expr::EvalResult result;
  5310. if (E->EvaluateAsRValue(result, C))
  5311. return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
  5312. // I think we only want to look through implicit casts here; if the
  5313. // user has an explicit widening cast, we should treat the value as
  5314. // being of the new, wider type.
  5315. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  5316. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  5317. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  5318. IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
  5319. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  5320. // Assume that non-integer casts can span the full range of the type.
  5321. if (!isIntegerCast)
  5322. return OutputTypeRange;
  5323. IntRange SubRange
  5324. = GetExprRange(C, CE->getSubExpr(),
  5325. std::min(MaxWidth, OutputTypeRange.Width));
  5326. // Bail out if the subexpr's range is as wide as the cast type.
  5327. if (SubRange.Width >= OutputTypeRange.Width)
  5328. return OutputTypeRange;
  5329. // Otherwise, we take the smaller width, and we're non-negative if
  5330. // either the output type or the subexpr is.
  5331. return IntRange(SubRange.Width,
  5332. SubRange.NonNegative || OutputTypeRange.NonNegative);
  5333. }
  5334. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  5335. // If we can fold the condition, just take that operand.
  5336. bool CondResult;
  5337. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  5338. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  5339. : CO->getFalseExpr(),
  5340. MaxWidth);
  5341. // Otherwise, conservatively merge.
  5342. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  5343. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  5344. return IntRange::join(L, R);
  5345. }
  5346. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  5347. switch (BO->getOpcode()) {
  5348. // Boolean-valued operations are single-bit and positive.
  5349. case BO_LAnd:
  5350. case BO_LOr:
  5351. case BO_LT:
  5352. case BO_GT:
  5353. case BO_LE:
  5354. case BO_GE:
  5355. case BO_EQ:
  5356. case BO_NE:
  5357. return IntRange::forBoolType();
  5358. // The type of the assignments is the type of the LHS, so the RHS
  5359. // is not necessarily the same type.
  5360. case BO_MulAssign:
  5361. case BO_DivAssign:
  5362. case BO_RemAssign:
  5363. case BO_AddAssign:
  5364. case BO_SubAssign:
  5365. case BO_XorAssign:
  5366. case BO_OrAssign:
  5367. // TODO: bitfields?
  5368. return IntRange::forValueOfType(C, GetExprType(E));
  5369. // Simple assignments just pass through the RHS, which will have
  5370. // been coerced to the LHS type.
  5371. case BO_Assign:
  5372. // TODO: bitfields?
  5373. return GetExprRange(C, BO->getRHS(), MaxWidth);
  5374. // Operations with opaque sources are black-listed.
  5375. case BO_PtrMemD:
  5376. case BO_PtrMemI:
  5377. return IntRange::forValueOfType(C, GetExprType(E));
  5378. // Bitwise-and uses the *infinum* of the two source ranges.
  5379. case BO_And:
  5380. case BO_AndAssign:
  5381. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  5382. GetExprRange(C, BO->getRHS(), MaxWidth));
  5383. // Left shift gets black-listed based on a judgement call.
  5384. case BO_Shl:
  5385. // ...except that we want to treat '1 << (blah)' as logically
  5386. // positive. It's an important idiom.
  5387. if (IntegerLiteral *I
  5388. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  5389. if (I->getValue() == 1) {
  5390. IntRange R = IntRange::forValueOfType(C, GetExprType(E));
  5391. return IntRange(R.Width, /*NonNegative*/ true);
  5392. }
  5393. }
  5394. // fallthrough
  5395. case BO_ShlAssign:
  5396. return IntRange::forValueOfType(C, GetExprType(E));
  5397. // Right shift by a constant can narrow its left argument.
  5398. case BO_Shr:
  5399. case BO_ShrAssign: {
  5400. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  5401. // If the shift amount is a positive constant, drop the width by
  5402. // that much.
  5403. llvm::APSInt shift;
  5404. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  5405. shift.isNonNegative()) {
  5406. unsigned zext = shift.getZExtValue();
  5407. if (zext >= L.Width)
  5408. L.Width = (L.NonNegative ? 0 : 1);
  5409. else
  5410. L.Width -= zext;
  5411. }
  5412. return L;
  5413. }
  5414. // Comma acts as its right operand.
  5415. case BO_Comma:
  5416. return GetExprRange(C, BO->getRHS(), MaxWidth);
  5417. // Black-list pointer subtractions.
  5418. case BO_Sub:
  5419. if (BO->getLHS()->getType()->isPointerType())
  5420. return IntRange::forValueOfType(C, GetExprType(E));
  5421. break;
  5422. // The width of a division result is mostly determined by the size
  5423. // of the LHS.
  5424. case BO_Div: {
  5425. // Don't 'pre-truncate' the operands.
  5426. unsigned opWidth = C.getIntWidth(GetExprType(E));
  5427. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  5428. // If the divisor is constant, use that.
  5429. llvm::APSInt divisor;
  5430. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  5431. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  5432. if (log2 >= L.Width)
  5433. L.Width = (L.NonNegative ? 0 : 1);
  5434. else
  5435. L.Width = std::min(L.Width - log2, MaxWidth);
  5436. return L;
  5437. }
  5438. // Otherwise, just use the LHS's width.
  5439. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  5440. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  5441. }
  5442. // The result of a remainder can't be larger than the result of
  5443. // either side.
  5444. case BO_Rem: {
  5445. // Don't 'pre-truncate' the operands.
  5446. unsigned opWidth = C.getIntWidth(GetExprType(E));
  5447. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  5448. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  5449. IntRange meet = IntRange::meet(L, R);
  5450. meet.Width = std::min(meet.Width, MaxWidth);
  5451. return meet;
  5452. }
  5453. // The default behavior is okay for these.
  5454. case BO_Mul:
  5455. case BO_Add:
  5456. case BO_Xor:
  5457. case BO_Or:
  5458. break;
  5459. }
  5460. // The default case is to treat the operation as if it were closed
  5461. // on the narrowest type that encompasses both operands.
  5462. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  5463. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  5464. return IntRange::join(L, R);
  5465. }
  5466. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  5467. switch (UO->getOpcode()) {
  5468. // Boolean-valued operations are white-listed.
  5469. case UO_LNot:
  5470. return IntRange::forBoolType();
  5471. // Operations with opaque sources are black-listed.
  5472. case UO_Deref:
  5473. case UO_AddrOf: // should be impossible
  5474. return IntRange::forValueOfType(C, GetExprType(E));
  5475. default:
  5476. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  5477. }
  5478. }
  5479. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  5480. return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
  5481. if (FieldDecl *BitField = E->getSourceBitField())
  5482. return IntRange(BitField->getBitWidthValue(C),
  5483. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  5484. return IntRange::forValueOfType(C, GetExprType(E));
  5485. }
  5486. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  5487. return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
  5488. }
  5489. /// Checks whether the given value, which currently has the given
  5490. /// source semantics, has the same value when coerced through the
  5491. /// target semantics.
  5492. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  5493. const llvm::fltSemantics &Src,
  5494. const llvm::fltSemantics &Tgt) {
  5495. llvm::APFloat truncated = value;
  5496. bool ignored;
  5497. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  5498. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  5499. return truncated.bitwiseIsEqual(value);
  5500. }
  5501. /// Checks whether the given value, which currently has the given
  5502. /// source semantics, has the same value when coerced through the
  5503. /// target semantics.
  5504. ///
  5505. /// The value might be a vector of floats (or a complex number).
  5506. static bool IsSameFloatAfterCast(const APValue &value,
  5507. const llvm::fltSemantics &Src,
  5508. const llvm::fltSemantics &Tgt) {
  5509. if (value.isFloat())
  5510. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  5511. if (value.isVector()) {
  5512. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  5513. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  5514. return false;
  5515. return true;
  5516. }
  5517. assert(value.isComplexFloat());
  5518. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  5519. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  5520. }
  5521. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  5522. static bool IsZero(Sema &S, Expr *E) {
  5523. // Suppress cases where we are comparing against an enum constant.
  5524. if (const DeclRefExpr *DR =
  5525. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  5526. if (isa<EnumConstantDecl>(DR->getDecl()))
  5527. return false;
  5528. // Suppress cases where the '0' value is expanded from a macro.
  5529. if (E->getLocStart().isMacroID())
  5530. return false;
  5531. llvm::APSInt Value;
  5532. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  5533. }
  5534. static bool HasEnumType(Expr *E) {
  5535. // Strip off implicit integral promotions.
  5536. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  5537. if (ICE->getCastKind() != CK_IntegralCast &&
  5538. ICE->getCastKind() != CK_NoOp)
  5539. break;
  5540. E = ICE->getSubExpr();
  5541. }
  5542. return E->getType()->isEnumeralType();
  5543. }
  5544. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  5545. // Disable warning in template instantiations.
  5546. if (!S.ActiveTemplateInstantiations.empty())
  5547. return;
  5548. BinaryOperatorKind op = E->getOpcode();
  5549. if (E->isValueDependent())
  5550. return;
  5551. if (op == BO_LT && IsZero(S, E->getRHS())) {
  5552. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  5553. << "< 0" << "false" << HasEnumType(E->getLHS())
  5554. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5555. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  5556. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  5557. << ">= 0" << "true" << HasEnumType(E->getLHS())
  5558. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5559. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  5560. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  5561. << "0 >" << "false" << HasEnumType(E->getRHS())
  5562. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5563. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  5564. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  5565. << "0 <=" << "true" << HasEnumType(E->getRHS())
  5566. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  5567. }
  5568. }
  5569. static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
  5570. Expr *Constant, Expr *Other,
  5571. llvm::APSInt Value,
  5572. bool RhsConstant) {
  5573. // Disable warning in template instantiations.
  5574. if (!S.ActiveTemplateInstantiations.empty())
  5575. return;
  5576. // TODO: Investigate using GetExprRange() to get tighter bounds
  5577. // on the bit ranges.
  5578. QualType OtherT = Other->getType();
  5579. if (const auto *AT = OtherT->getAs<AtomicType>())
  5580. OtherT = AT->getValueType();
  5581. IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
  5582. unsigned OtherWidth = OtherRange.Width;
  5583. bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
  5584. // 0 values are handled later by CheckTrivialUnsignedComparison().
  5585. if ((Value == 0) && (!OtherIsBooleanType))
  5586. return;
  5587. BinaryOperatorKind op = E->getOpcode();
  5588. bool IsTrue = true;
  5589. // Used for diagnostic printout.
  5590. enum {
  5591. LiteralConstant = 0,
  5592. CXXBoolLiteralTrue,
  5593. CXXBoolLiteralFalse
  5594. } LiteralOrBoolConstant = LiteralConstant;
  5595. if (!OtherIsBooleanType) {
  5596. QualType ConstantT = Constant->getType();
  5597. QualType CommonT = E->getLHS()->getType();
  5598. if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
  5599. return;
  5600. assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
  5601. "comparison with non-integer type");
  5602. bool ConstantSigned = ConstantT->isSignedIntegerType();
  5603. bool CommonSigned = CommonT->isSignedIntegerType();
  5604. bool EqualityOnly = false;
  5605. if (CommonSigned) {
  5606. // The common type is signed, therefore no signed to unsigned conversion.
  5607. if (!OtherRange.NonNegative) {
  5608. // Check that the constant is representable in type OtherT.
  5609. if (ConstantSigned) {
  5610. if (OtherWidth >= Value.getMinSignedBits())
  5611. return;
  5612. } else { // !ConstantSigned
  5613. if (OtherWidth >= Value.getActiveBits() + 1)
  5614. return;
  5615. }
  5616. } else { // !OtherSigned
  5617. // Check that the constant is representable in type OtherT.
  5618. // Negative values are out of range.
  5619. if (ConstantSigned) {
  5620. if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
  5621. return;
  5622. } else { // !ConstantSigned
  5623. if (OtherWidth >= Value.getActiveBits())
  5624. return;
  5625. }
  5626. }
  5627. } else { // !CommonSigned
  5628. if (OtherRange.NonNegative) {
  5629. if (OtherWidth >= Value.getActiveBits())
  5630. return;
  5631. } else { // OtherSigned
  5632. assert(!ConstantSigned &&
  5633. "Two signed types converted to unsigned types.");
  5634. // Check to see if the constant is representable in OtherT.
  5635. if (OtherWidth > Value.getActiveBits())
  5636. return;
  5637. // Check to see if the constant is equivalent to a negative value
  5638. // cast to CommonT.
  5639. if (S.Context.getIntWidth(ConstantT) ==
  5640. S.Context.getIntWidth(CommonT) &&
  5641. Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
  5642. return;
  5643. // The constant value rests between values that OtherT can represent
  5644. // after conversion. Relational comparison still works, but equality
  5645. // comparisons will be tautological.
  5646. EqualityOnly = true;
  5647. }
  5648. }
  5649. bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
  5650. if (op == BO_EQ || op == BO_NE) {
  5651. IsTrue = op == BO_NE;
  5652. } else if (EqualityOnly) {
  5653. return;
  5654. } else if (RhsConstant) {
  5655. if (op == BO_GT || op == BO_GE)
  5656. IsTrue = !PositiveConstant;
  5657. else // op == BO_LT || op == BO_LE
  5658. IsTrue = PositiveConstant;
  5659. } else {
  5660. if (op == BO_LT || op == BO_LE)
  5661. IsTrue = !PositiveConstant;
  5662. else // op == BO_GT || op == BO_GE
  5663. IsTrue = PositiveConstant;
  5664. }
  5665. } else {
  5666. // Other isKnownToHaveBooleanValue
  5667. enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
  5668. enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
  5669. enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
  5670. static const struct LinkedConditions {
  5671. CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
  5672. CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
  5673. CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
  5674. CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
  5675. CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
  5676. CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
  5677. } TruthTable = {
  5678. // Constant on LHS. | Constant on RHS. |
  5679. // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
  5680. { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
  5681. { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
  5682. { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
  5683. { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
  5684. { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
  5685. { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
  5686. };
  5687. bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
  5688. enum ConstantValue ConstVal = Zero;
  5689. if (Value.isUnsigned() || Value.isNonNegative()) {
  5690. if (Value == 0) {
  5691. LiteralOrBoolConstant =
  5692. ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
  5693. ConstVal = Zero;
  5694. } else if (Value == 1) {
  5695. LiteralOrBoolConstant =
  5696. ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
  5697. ConstVal = One;
  5698. } else {
  5699. LiteralOrBoolConstant = LiteralConstant;
  5700. ConstVal = GT_One;
  5701. }
  5702. } else {
  5703. ConstVal = LT_Zero;
  5704. }
  5705. CompareBoolWithConstantResult CmpRes;
  5706. switch (op) {
  5707. case BO_LT:
  5708. CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
  5709. break;
  5710. case BO_GT:
  5711. CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
  5712. break;
  5713. case BO_LE:
  5714. CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
  5715. break;
  5716. case BO_GE:
  5717. CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
  5718. break;
  5719. case BO_EQ:
  5720. CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
  5721. break;
  5722. case BO_NE:
  5723. CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
  5724. break;
  5725. default:
  5726. CmpRes = Unkwn;
  5727. break;
  5728. }
  5729. if (CmpRes == AFals) {
  5730. IsTrue = false;
  5731. } else if (CmpRes == ATrue) {
  5732. IsTrue = true;
  5733. } else {
  5734. return;
  5735. }
  5736. }
  5737. // If this is a comparison to an enum constant, include that
  5738. // constant in the diagnostic.
  5739. const EnumConstantDecl *ED = nullptr;
  5740. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
  5741. ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
  5742. SmallString<64> PrettySourceValue;
  5743. llvm::raw_svector_ostream OS(PrettySourceValue);
  5744. if (ED)
  5745. OS << '\'' << *ED << "' (" << Value << ")";
  5746. else
  5747. OS << Value;
  5748. S.DiagRuntimeBehavior(
  5749. E->getOperatorLoc(), E,
  5750. S.PDiag(diag::warn_out_of_range_compare)
  5751. << OS.str() << LiteralOrBoolConstant
  5752. << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
  5753. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
  5754. }
  5755. /// Analyze the operands of the given comparison. Implements the
  5756. /// fallback case from AnalyzeComparison.
  5757. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  5758. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  5759. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  5760. }
  5761. /// \brief Implements -Wsign-compare.
  5762. ///
  5763. /// \param E the binary operator to check for warnings
  5764. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  5765. // The type the comparison is being performed in.
  5766. QualType T = E->getLHS()->getType();
  5767. // HLSL Change Starts
  5768. // HLSL has a different set of standard conversions allowed. Until
  5769. // the warning analysis is updated, simply skip this step.
  5770. if (S.getLangOpts().HLSL) {
  5771. return;
  5772. }
  5773. // HLSL Change Ends
  5774. // Only analyze comparison operators where both sides have been converted to
  5775. // the same type.
  5776. if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
  5777. return AnalyzeImpConvsInComparison(S, E);
  5778. // Don't analyze value-dependent comparisons directly.
  5779. if (E->isValueDependent())
  5780. return AnalyzeImpConvsInComparison(S, E);
  5781. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  5782. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  5783. bool IsComparisonConstant = false;
  5784. // Check whether an integer constant comparison results in a value
  5785. // of 'true' or 'false'.
  5786. if (T->isIntegralType(S.Context)) {
  5787. llvm::APSInt RHSValue;
  5788. bool IsRHSIntegralLiteral =
  5789. RHS->isIntegerConstantExpr(RHSValue, S.Context);
  5790. llvm::APSInt LHSValue;
  5791. bool IsLHSIntegralLiteral =
  5792. LHS->isIntegerConstantExpr(LHSValue, S.Context);
  5793. if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
  5794. DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
  5795. else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
  5796. DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
  5797. else
  5798. IsComparisonConstant =
  5799. (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
  5800. } else if (!T->hasUnsignedIntegerRepresentation())
  5801. IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
  5802. // We don't do anything special if this isn't an unsigned integral
  5803. // comparison: we're only interested in integral comparisons, and
  5804. // signed comparisons only happen in cases we don't care to warn about.
  5805. //
  5806. // We also don't care about value-dependent expressions or expressions
  5807. // whose result is a constant.
  5808. if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
  5809. return AnalyzeImpConvsInComparison(S, E);
  5810. // Check to see if one of the (unmodified) operands is of different
  5811. // signedness.
  5812. Expr *signedOperand, *unsignedOperand;
  5813. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  5814. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  5815. "unsigned comparison between two signed integer expressions?");
  5816. signedOperand = LHS;
  5817. unsignedOperand = RHS;
  5818. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  5819. signedOperand = RHS;
  5820. unsignedOperand = LHS;
  5821. } else {
  5822. CheckTrivialUnsignedComparison(S, E);
  5823. return AnalyzeImpConvsInComparison(S, E);
  5824. }
  5825. // Otherwise, calculate the effective range of the signed operand.
  5826. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  5827. // Go ahead and analyze implicit conversions in the operands. Note
  5828. // that we skip the implicit conversions on both sides.
  5829. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  5830. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  5831. // If the signed range is non-negative, -Wsign-compare won't fire,
  5832. // but we should still check for comparisons which are always true
  5833. // or false.
  5834. if (signedRange.NonNegative)
  5835. return CheckTrivialUnsignedComparison(S, E);
  5836. // For (in)equality comparisons, if the unsigned operand is a
  5837. // constant which cannot collide with a overflowed signed operand,
  5838. // then reinterpreting the signed operand as unsigned will not
  5839. // change the result of the comparison.
  5840. if (E->isEqualityOp()) {
  5841. unsigned comparisonWidth = S.Context.getIntWidth(T);
  5842. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  5843. // We should never be unable to prove that the unsigned operand is
  5844. // non-negative.
  5845. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  5846. if (unsignedRange.Width < comparisonWidth)
  5847. return;
  5848. }
  5849. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  5850. S.PDiag(diag::warn_mixed_sign_comparison)
  5851. << LHS->getType() << RHS->getType()
  5852. << LHS->getSourceRange() << RHS->getSourceRange());
  5853. }
  5854. /// Analyzes an attempt to assign the given value to a bitfield.
  5855. ///
  5856. /// Returns true if there was something fishy about the attempt.
  5857. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  5858. SourceLocation InitLoc) {
  5859. assert(Bitfield->isBitField());
  5860. if (Bitfield->isInvalidDecl())
  5861. return false;
  5862. // White-list bool bitfields.
  5863. if (Bitfield->getType()->isBooleanType())
  5864. return false;
  5865. // Ignore value- or type-dependent expressions.
  5866. if (Bitfield->getBitWidth()->isValueDependent() ||
  5867. Bitfield->getBitWidth()->isTypeDependent() ||
  5868. Init->isValueDependent() ||
  5869. Init->isTypeDependent())
  5870. return false;
  5871. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  5872. llvm::APSInt Value;
  5873. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  5874. return false;
  5875. unsigned OriginalWidth = Value.getBitWidth();
  5876. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  5877. if (OriginalWidth <= FieldWidth)
  5878. return false;
  5879. // Compute the value which the bitfield will contain.
  5880. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  5881. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  5882. // Check whether the stored value is equal to the original value.
  5883. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  5884. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  5885. return false;
  5886. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  5887. // therefore don't strictly fit into a signed bitfield of width 1.
  5888. if (FieldWidth == 1 && Value == 1)
  5889. return false;
  5890. std::string PrettyValue = Value.toString(10);
  5891. std::string PrettyTrunc = TruncatedValue.toString(10);
  5892. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  5893. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  5894. << Init->getSourceRange();
  5895. return true;
  5896. }
  5897. /// Analyze the given simple or compound assignment for warning-worthy
  5898. /// operations.
  5899. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  5900. // Just recurse on the LHS.
  5901. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  5902. // We want to recurse on the RHS as normal unless we're assigning to
  5903. // a bitfield.
  5904. if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
  5905. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  5906. E->getOperatorLoc())) {
  5907. // Recurse, ignoring any implicit conversions on the RHS.
  5908. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  5909. E->getOperatorLoc());
  5910. }
  5911. }
  5912. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  5913. }
  5914. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  5915. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  5916. SourceLocation CContext, unsigned diag,
  5917. bool pruneControlFlow = false) {
  5918. if (pruneControlFlow) {
  5919. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  5920. S.PDiag(diag)
  5921. << SourceType << T << E->getSourceRange()
  5922. << SourceRange(CContext));
  5923. return;
  5924. }
  5925. S.Diag(E->getExprLoc(), diag)
  5926. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  5927. }
  5928. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  5929. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  5930. SourceLocation CContext, unsigned diag,
  5931. bool pruneControlFlow = false) {
  5932. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  5933. }
  5934. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  5935. /// cast wouldn't lose information.
  5936. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  5937. SourceLocation CContext) {
  5938. // Try to convert the literal exactly to an integer. If we can, don't warn.
  5939. bool isExact = false;
  5940. const llvm::APFloat &Value = FL->getValue();
  5941. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  5942. T->hasUnsignedIntegerRepresentation());
  5943. if (Value.convertToInteger(IntegerValue,
  5944. llvm::APFloat::rmTowardZero, &isExact)
  5945. == llvm::APFloat::opOK && isExact)
  5946. return;
  5947. // FIXME: Force the precision of the source value down so we don't print
  5948. // digits which are usually useless (we don't really care here if we
  5949. // truncate a digit by accident in edge cases). Ideally, APFloat::toString
  5950. // would automatically print the shortest representation, but it's a bit
  5951. // tricky to implement.
  5952. SmallString<16> PrettySourceValue;
  5953. unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
  5954. precision = (precision * 59 + 195) / 196;
  5955. Value.toString(PrettySourceValue, precision);
  5956. SmallString<16> PrettyTargetValue;
  5957. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  5958. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  5959. else
  5960. IntegerValue.toString(PrettyTargetValue);
  5961. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  5962. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  5963. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  5964. }
  5965. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  5966. if (!Range.Width) return "0";
  5967. llvm::APSInt ValueInRange = Value;
  5968. ValueInRange.setIsSigned(!Range.NonNegative);
  5969. ValueInRange = ValueInRange.trunc(Range.Width);
  5970. return ValueInRange.toString(10);
  5971. }
  5972. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  5973. if (!isa<ImplicitCastExpr>(Ex))
  5974. return false;
  5975. Expr *InnerE = Ex->IgnoreParenImpCasts();
  5976. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  5977. const Type *Source =
  5978. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  5979. if (Target->isDependentType())
  5980. return false;
  5981. const BuiltinType *FloatCandidateBT =
  5982. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  5983. const Type *BoolCandidateType = ToBool ? Target : Source;
  5984. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  5985. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  5986. }
  5987. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  5988. SourceLocation CC) {
  5989. unsigned NumArgs = TheCall->getNumArgs();
  5990. for (unsigned i = 0; i < NumArgs; ++i) {
  5991. Expr *CurrA = TheCall->getArg(i);
  5992. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  5993. continue;
  5994. bool IsSwapped = ((i > 0) &&
  5995. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  5996. IsSwapped |= ((i < (NumArgs - 1)) &&
  5997. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  5998. if (IsSwapped) {
  5999. // Warn on this floating-point to bool conversion.
  6000. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  6001. CurrA->getType(), CC,
  6002. diag::warn_impcast_floating_point_to_bool);
  6003. }
  6004. }
  6005. }
  6006. static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
  6007. SourceLocation CC) {
  6008. if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
  6009. E->getExprLoc()))
  6010. return;
  6011. // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
  6012. const Expr::NullPointerConstantKind NullKind =
  6013. E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
  6014. if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
  6015. return;
  6016. // Return if target type is a safe conversion.
  6017. if (T->isAnyPointerType() || T->isBlockPointerType() ||
  6018. T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
  6019. return;
  6020. SourceLocation Loc = E->getSourceRange().getBegin();
  6021. // __null is usually wrapped in a macro. Go up a macro if that is the case.
  6022. if (NullKind == Expr::NPCK_GNUNull) {
  6023. if (Loc.isMacroID())
  6024. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  6025. }
  6026. // Only warn if the null and context location are in the same macro expansion.
  6027. if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
  6028. return;
  6029. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  6030. << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
  6031. << FixItHint::CreateReplacement(Loc,
  6032. S.getFixItZeroLiteralForType(T, Loc));
  6033. }
  6034. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  6035. ObjCArrayLiteral *ArrayLiteral);
  6036. static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
  6037. ObjCDictionaryLiteral *DictionaryLiteral);
  6038. /// Check a single element within a collection literal against the
  6039. /// target element type.
  6040. static void checkObjCCollectionLiteralElement(Sema &S,
  6041. QualType TargetElementType,
  6042. Expr *Element,
  6043. unsigned ElementKind) {
  6044. // Skip a bitcast to 'id' or qualified 'id'.
  6045. if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
  6046. if (ICE->getCastKind() == CK_BitCast &&
  6047. ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
  6048. Element = ICE->getSubExpr();
  6049. }
  6050. QualType ElementType = Element->getType();
  6051. ExprResult ElementResult(Element);
  6052. if (ElementType->getAs<ObjCObjectPointerType>() &&
  6053. S.CheckSingleAssignmentConstraints(TargetElementType,
  6054. ElementResult,
  6055. false, false)
  6056. != Sema::Compatible) {
  6057. S.Diag(Element->getLocStart(),
  6058. diag::warn_objc_collection_literal_element)
  6059. << ElementType << ElementKind << TargetElementType
  6060. << Element->getSourceRange();
  6061. }
  6062. if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
  6063. checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
  6064. else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
  6065. checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
  6066. }
  6067. /// Check an Objective-C array literal being converted to the given
  6068. /// target type.
  6069. static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
  6070. ObjCArrayLiteral *ArrayLiteral) {
  6071. if (!S.NSArrayDecl)
  6072. return;
  6073. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  6074. if (!TargetObjCPtr)
  6075. return;
  6076. if (TargetObjCPtr->isUnspecialized() ||
  6077. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  6078. != S.NSArrayDecl->getCanonicalDecl())
  6079. return;
  6080. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  6081. if (TypeArgs.size() != 1)
  6082. return;
  6083. QualType TargetElementType = TypeArgs[0];
  6084. for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
  6085. checkObjCCollectionLiteralElement(S, TargetElementType,
  6086. ArrayLiteral->getElement(I),
  6087. 0);
  6088. }
  6089. }
  6090. /// Check an Objective-C dictionary literal being converted to the given
  6091. /// target type.
  6092. static void checkObjCDictionaryLiteral(
  6093. Sema &S, QualType TargetType,
  6094. ObjCDictionaryLiteral *DictionaryLiteral) {
  6095. if (!S.NSDictionaryDecl)
  6096. return;
  6097. const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
  6098. if (!TargetObjCPtr)
  6099. return;
  6100. if (TargetObjCPtr->isUnspecialized() ||
  6101. TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
  6102. != S.NSDictionaryDecl->getCanonicalDecl())
  6103. return;
  6104. auto TypeArgs = TargetObjCPtr->getTypeArgs();
  6105. if (TypeArgs.size() != 2)
  6106. return;
  6107. QualType TargetKeyType = TypeArgs[0];
  6108. QualType TargetObjectType = TypeArgs[1];
  6109. for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
  6110. auto Element = DictionaryLiteral->getKeyValueElement(I);
  6111. checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
  6112. checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
  6113. }
  6114. }
  6115. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  6116. SourceLocation CC, bool *ICContext = nullptr) {
  6117. if (E->isTypeDependent() || E->isValueDependent()) return;
  6118. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  6119. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  6120. if (Source == Target) return;
  6121. if (Target->isDependentType()) return;
  6122. // If the conversion context location is invalid don't complain. We also
  6123. // don't want to emit a warning if the issue occurs from the expansion of
  6124. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  6125. // delay this check as long as possible. Once we detect we are in that
  6126. // scenario, we just return.
  6127. if (CC.isInvalid())
  6128. return;
  6129. // Diagnose implicit casts to bool.
  6130. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  6131. if (isa<StringLiteral>(E))
  6132. // Warn on string literal to bool. Checks for string literals in logical
  6133. // and expressions, for instance, assert(0 && "error here"), are
  6134. // prevented by a check in AnalyzeImplicitConversions().
  6135. return DiagnoseImpCast(S, E, T, CC,
  6136. diag::warn_impcast_string_literal_to_bool);
  6137. if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
  6138. isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
  6139. // This covers the literal expressions that evaluate to Objective-C
  6140. // objects.
  6141. return DiagnoseImpCast(S, E, T, CC,
  6142. diag::warn_impcast_objective_c_literal_to_bool);
  6143. }
  6144. if (Source->isPointerType() || Source->canDecayToPointerType()) {
  6145. // Warn on pointer to bool conversion that is always true.
  6146. S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
  6147. SourceRange(CC));
  6148. }
  6149. }
  6150. // Check implicit casts from Objective-C collection literals to specialized
  6151. // collection types, e.g., NSArray<NSString *> *.
  6152. if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
  6153. checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
  6154. else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
  6155. checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
  6156. // Strip vector types.
  6157. if (isa<VectorType>(Source)) {
  6158. if (!isa<VectorType>(Target)) {
  6159. if (S.SourceMgr.isInSystemMacro(CC))
  6160. return;
  6161. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  6162. }
  6163. // If the vector cast is cast between two vectors of the same size, it is
  6164. // a bitcast, not a conversion.
  6165. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  6166. return;
  6167. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  6168. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  6169. }
  6170. if (auto VecTy = dyn_cast<VectorType>(Target))
  6171. Target = VecTy->getElementType().getTypePtr();
  6172. // Strip complex types.
  6173. if (isa<ComplexType>(Source)) {
  6174. if (!isa<ComplexType>(Target)) {
  6175. if (S.SourceMgr.isInSystemMacro(CC))
  6176. return;
  6177. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  6178. }
  6179. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  6180. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  6181. }
  6182. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  6183. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  6184. // If the source is floating point...
  6185. if (SourceBT && SourceBT->isFloatingPoint()) {
  6186. // ...and the target is floating point...
  6187. if (TargetBT && TargetBT->isFloatingPoint()) {
  6188. // ...then warn if we're dropping FP rank.
  6189. // HLSL Change - unless source is literal float
  6190. if (SourceBT->getKind() == BuiltinType::LitFloat)
  6191. return;
  6192. // Builtin FP kinds are ordered by increasing FP rank.
  6193. if (SourceBT->getKind() > TargetBT->getKind()) {
  6194. // Don't warn about float constants that are precisely
  6195. // representable in the target type.
  6196. Expr::EvalResult result;
  6197. if (E->EvaluateAsRValue(result, S.Context)) {
  6198. // Value might be a float, a float vector, or a float complex.
  6199. if (IsSameFloatAfterCast(result.Val,
  6200. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  6201. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  6202. return;
  6203. }
  6204. if (S.SourceMgr.isInSystemMacro(CC))
  6205. return;
  6206. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  6207. }
  6208. return;
  6209. }
  6210. // If the target is integral, always warn.
  6211. if (TargetBT && TargetBT->isInteger()) {
  6212. if (S.SourceMgr.isInSystemMacro(CC))
  6213. return;
  6214. Expr *InnerE = E->IgnoreParenImpCasts();
  6215. // We also want to warn on, e.g., "int i = -1.234"
  6216. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  6217. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  6218. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  6219. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  6220. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  6221. } else {
  6222. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  6223. }
  6224. }
  6225. // If the target is bool, warn if expr is a function or method call.
  6226. if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
  6227. isa<CallExpr>(E)) {
  6228. // Check last argument of function call to see if it is an
  6229. // implicit cast from a type matching the type the result
  6230. // is being cast to.
  6231. CallExpr *CEx = cast<CallExpr>(E);
  6232. unsigned NumArgs = CEx->getNumArgs();
  6233. if (NumArgs > 0) {
  6234. Expr *LastA = CEx->getArg(NumArgs - 1);
  6235. Expr *InnerE = LastA->IgnoreParenImpCasts();
  6236. const Type *InnerType =
  6237. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  6238. if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
  6239. // Warn on this floating-point to bool conversion
  6240. DiagnoseImpCast(S, E, T, CC,
  6241. diag::warn_impcast_floating_point_to_bool);
  6242. }
  6243. }
  6244. }
  6245. return;
  6246. }
  6247. DiagnoseNullConversion(S, E, T, CC);
  6248. if (!Source->isIntegerType() || !Target->isIntegerType())
  6249. return;
  6250. // TODO: remove this early return once the false positives for constant->bool
  6251. // in templates, macros, etc, are reduced or removed.
  6252. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  6253. return;
  6254. IntRange SourceRange = GetExprRange(S.Context, E);
  6255. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  6256. if (SourceRange.Width > TargetRange.Width) {
  6257. // If the source is a constant, use a default-on diagnostic.
  6258. // TODO: this should happen for bitfield stores, too.
  6259. llvm::APSInt Value(32);
  6260. if (E->isIntegerConstantExpr(Value, S.Context)) {
  6261. if (S.SourceMgr.isInSystemMacro(CC))
  6262. return;
  6263. std::string PrettySourceValue = Value.toString(10);
  6264. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  6265. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  6266. S.PDiag(diag::warn_impcast_integer_precision_constant)
  6267. << PrettySourceValue << PrettyTargetValue
  6268. << E->getType() << T << E->getSourceRange()
  6269. << clang::SourceRange(CC));
  6270. return;
  6271. }
  6272. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  6273. if (S.SourceMgr.isInSystemMacro(CC))
  6274. return;
  6275. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  6276. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  6277. /* pruneControlFlow */ true);
  6278. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  6279. }
  6280. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  6281. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  6282. SourceRange.Width == TargetRange.Width)) {
  6283. if (S.SourceMgr.isInSystemMacro(CC))
  6284. return;
  6285. unsigned DiagID = diag::warn_impcast_integer_sign;
  6286. // Traditionally, gcc has warned about this under -Wsign-compare.
  6287. // We also want to warn about it in -Wconversion.
  6288. // So if -Wconversion is off, use a completely identical diagnostic
  6289. // in the sign-compare group.
  6290. // The conditional-checking code will
  6291. if (ICContext) {
  6292. DiagID = diag::warn_impcast_integer_sign_conditional;
  6293. *ICContext = true;
  6294. }
  6295. return DiagnoseImpCast(S, E, T, CC, DiagID);
  6296. }
  6297. // Diagnose conversions between different enumeration types.
  6298. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  6299. // type, to give us better diagnostics.
  6300. QualType SourceType = E->getType();
  6301. if (!S.getLangOpts().CPlusPlus) {
  6302. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6303. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  6304. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  6305. SourceType = S.Context.getTypeDeclType(Enum);
  6306. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  6307. }
  6308. }
  6309. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  6310. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  6311. if (SourceEnum->getDecl()->hasNameForLinkage() &&
  6312. TargetEnum->getDecl()->hasNameForLinkage() &&
  6313. SourceEnum != TargetEnum) {
  6314. if (S.SourceMgr.isInSystemMacro(CC))
  6315. return;
  6316. return DiagnoseImpCast(S, E, SourceType, T, CC,
  6317. diag::warn_impcast_different_enum_types);
  6318. }
  6319. return;
  6320. }
  6321. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  6322. SourceLocation CC, QualType T);
  6323. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  6324. SourceLocation CC, bool &ICContext) {
  6325. E = E->IgnoreParenImpCasts();
  6326. if (isa<ConditionalOperator>(E))
  6327. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  6328. AnalyzeImplicitConversions(S, E, CC);
  6329. if (E->getType() != T)
  6330. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  6331. return;
  6332. }
  6333. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  6334. SourceLocation CC, QualType T) {
  6335. AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
  6336. bool Suspicious = false;
  6337. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  6338. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  6339. // If -Wconversion would have warned about either of the candidates
  6340. // for a signedness conversion to the context type...
  6341. if (!Suspicious) return;
  6342. // ...but it's currently ignored...
  6343. if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
  6344. return;
  6345. // ...then check whether it would have warned about either of the
  6346. // candidates for a signedness conversion to the condition type.
  6347. if (E->getType() == T) return;
  6348. Suspicious = false;
  6349. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  6350. E->getType(), CC, &Suspicious);
  6351. if (!Suspicious)
  6352. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  6353. E->getType(), CC, &Suspicious);
  6354. }
  6355. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  6356. /// Input argument E is a logical expression.
  6357. static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
  6358. if (S.getLangOpts().Bool)
  6359. return;
  6360. CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
  6361. }
  6362. /// AnalyzeImplicitConversions - Find and report any interesting
  6363. /// implicit conversions in the given expression. There are a couple
  6364. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  6365. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  6366. QualType T = OrigE->getType();
  6367. Expr *E = OrigE->IgnoreParenImpCasts();
  6368. if (E->isTypeDependent() || E->isValueDependent())
  6369. return;
  6370. // For conditional operators, we analyze the arguments as if they
  6371. // were being fed directly into the output.
  6372. if (isa<ConditionalOperator>(E)) {
  6373. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  6374. CheckConditionalOperator(S, CO, CC, T);
  6375. return;
  6376. }
  6377. // Check implicit argument conversions for function calls.
  6378. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  6379. CheckImplicitArgumentConversions(S, Call, CC);
  6380. // Go ahead and check any implicit conversions we might have skipped.
  6381. // The non-canonical typecheck is just an optimization;
  6382. // CheckImplicitConversion will filter out dead implicit conversions.
  6383. if (E->getType() != T)
  6384. CheckImplicitConversion(S, E, T, CC);
  6385. // Now continue drilling into this expression.
  6386. if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
  6387. if (POE->getResultExpr())
  6388. E = POE->getResultExpr();
  6389. }
  6390. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  6391. if (OVE->getSourceExpr())
  6392. AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
  6393. return;
  6394. }
  6395. // Skip past explicit casts.
  6396. if (isa<ExplicitCastExpr>(E)) {
  6397. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  6398. return AnalyzeImplicitConversions(S, E, CC);
  6399. }
  6400. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6401. // Do a somewhat different check with comparison operators.
  6402. if (BO->isComparisonOp())
  6403. return AnalyzeComparison(S, BO);
  6404. // And with simple assignments.
  6405. if (BO->getOpcode() == BO_Assign)
  6406. return AnalyzeAssignment(S, BO);
  6407. }
  6408. // These break the otherwise-useful invariant below. Fortunately,
  6409. // we don't really need to recurse into them, because any internal
  6410. // expressions should have been analyzed already when they were
  6411. // built into statements.
  6412. if (isa<StmtExpr>(E)) return;
  6413. // Don't descend into unevaluated contexts.
  6414. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  6415. // Now just recurse over the expression's children.
  6416. CC = E->getExprLoc();
  6417. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  6418. bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
  6419. for (Stmt *SubStmt : E->children()) {
  6420. Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
  6421. if (!ChildExpr)
  6422. continue;
  6423. if (IsLogicalAndOperator &&
  6424. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  6425. // Ignore checking string literals that are in logical and operators.
  6426. // This is a common pattern for asserts.
  6427. continue;
  6428. AnalyzeImplicitConversions(S, ChildExpr, CC);
  6429. }
  6430. if (BO && BO->isLogicalOp()) {
  6431. Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
  6432. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  6433. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  6434. SubExpr = BO->getRHS()->IgnoreParenImpCasts();
  6435. if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
  6436. ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
  6437. }
  6438. if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
  6439. if (U->getOpcode() == UO_LNot)
  6440. ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
  6441. }
  6442. } // end anonymous namespace
  6443. enum {
  6444. AddressOf,
  6445. FunctionPointer,
  6446. ArrayPointer
  6447. };
  6448. // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
  6449. // Returns true when emitting a warning about taking the address of a reference.
  6450. static bool CheckForReference(Sema &SemaRef, const Expr *E,
  6451. PartialDiagnostic PD) {
  6452. E = E->IgnoreParenImpCasts();
  6453. const FunctionDecl *FD = nullptr;
  6454. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  6455. if (!DRE->getDecl()->getType()->isReferenceType())
  6456. return false;
  6457. } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  6458. if (!M->getMemberDecl()->getType()->isReferenceType())
  6459. return false;
  6460. } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
  6461. if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
  6462. return false;
  6463. FD = Call->getDirectCallee();
  6464. } else {
  6465. return false;
  6466. }
  6467. SemaRef.Diag(E->getExprLoc(), PD);
  6468. // If possible, point to location of function.
  6469. if (FD) {
  6470. SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
  6471. }
  6472. return true;
  6473. }
  6474. // Returns true if the SourceLocation is expanded from any macro body.
  6475. // Returns false if the SourceLocation is invalid, is from not in a macro
  6476. // expansion, or is from expanded from a top-level macro argument.
  6477. static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
  6478. if (Loc.isInvalid())
  6479. return false;
  6480. while (Loc.isMacroID()) {
  6481. if (SM.isMacroBodyExpansion(Loc))
  6482. return true;
  6483. Loc = SM.getImmediateMacroCallerLoc(Loc);
  6484. }
  6485. return false;
  6486. }
  6487. /// \brief Diagnose pointers that are always non-null.
  6488. /// \param E the expression containing the pointer
  6489. /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
  6490. /// compared to a null pointer
  6491. /// \param IsEqual True when the comparison is equal to a null pointer
  6492. /// \param Range Extra SourceRange to highlight in the diagnostic
  6493. void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
  6494. Expr::NullPointerConstantKind NullKind,
  6495. bool IsEqual, SourceRange Range) {
  6496. if (!E)
  6497. return;
  6498. // Don't warn inside macros.
  6499. if (E->getExprLoc().isMacroID()) {
  6500. const SourceManager &SM = getSourceManager();
  6501. if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
  6502. IsInAnyMacroBody(SM, Range.getBegin()))
  6503. return;
  6504. }
  6505. E = E->IgnoreImpCasts();
  6506. const bool IsCompare = NullKind != Expr::NPCK_NotNull;
  6507. if (isa<CXXThisExpr>(E)) {
  6508. unsigned DiagID = IsCompare ? diag::warn_this_null_compare
  6509. : diag::warn_this_bool_conversion;
  6510. Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
  6511. return;
  6512. }
  6513. bool IsAddressOf = false;
  6514. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  6515. if (UO->getOpcode() != UO_AddrOf)
  6516. return;
  6517. IsAddressOf = true;
  6518. E = UO->getSubExpr();
  6519. }
  6520. if (IsAddressOf) {
  6521. unsigned DiagID = IsCompare
  6522. ? diag::warn_address_of_reference_null_compare
  6523. : diag::warn_address_of_reference_bool_conversion;
  6524. PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
  6525. << IsEqual;
  6526. if (CheckForReference(*this, E, PD)) {
  6527. return;
  6528. }
  6529. }
  6530. // Expect to find a single Decl. Skip anything more complicated.
  6531. ValueDecl *D = nullptr;
  6532. if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
  6533. D = R->getDecl();
  6534. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  6535. D = M->getMemberDecl();
  6536. }
  6537. // Weak Decls can be null.
  6538. if (!D || D->isWeak())
  6539. return;
  6540. // Check for parameter decl with nonnull attribute
  6541. if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
  6542. if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
  6543. if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
  6544. unsigned NumArgs = FD->getNumParams();
  6545. llvm::SmallBitVector AttrNonNull(NumArgs);
  6546. for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
  6547. if (!NonNull->args_size()) {
  6548. AttrNonNull.set(0, NumArgs);
  6549. break;
  6550. }
  6551. for (unsigned Val : NonNull->args()) {
  6552. if (Val >= NumArgs)
  6553. continue;
  6554. AttrNonNull.set(Val);
  6555. }
  6556. }
  6557. if (!AttrNonNull.empty())
  6558. for (unsigned i = 0; i < NumArgs; ++i)
  6559. if (FD->getParamDecl(i) == PV &&
  6560. (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
  6561. std::string Str;
  6562. llvm::raw_string_ostream S(Str);
  6563. E->printPretty(S, nullptr, getPrintingPolicy());
  6564. unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
  6565. : diag::warn_cast_nonnull_to_bool;
  6566. Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
  6567. << Range << IsEqual;
  6568. return;
  6569. }
  6570. }
  6571. }
  6572. QualType T = D->getType();
  6573. const bool IsArray = T->isArrayType();
  6574. const bool IsFunction = T->isFunctionType();
  6575. // Address of function is used to silence the function warning.
  6576. if (IsAddressOf && IsFunction) {
  6577. return;
  6578. }
  6579. // Found nothing.
  6580. if (!IsAddressOf && !IsFunction && !IsArray)
  6581. return;
  6582. // Pretty print the expression for the diagnostic.
  6583. std::string Str;
  6584. llvm::raw_string_ostream S(Str);
  6585. E->printPretty(S, nullptr, getPrintingPolicy());
  6586. unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
  6587. : diag::warn_impcast_pointer_to_bool;
  6588. unsigned DiagType;
  6589. if (IsAddressOf)
  6590. DiagType = AddressOf;
  6591. else if (IsFunction)
  6592. DiagType = FunctionPointer;
  6593. else if (IsArray)
  6594. DiagType = ArrayPointer;
  6595. else
  6596. llvm_unreachable("Could not determine diagnostic.");
  6597. Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
  6598. << Range << IsEqual;
  6599. if (!IsFunction)
  6600. return;
  6601. // Suggest '&' to silence the function warning.
  6602. Diag(E->getExprLoc(), diag::note_function_warning_silence)
  6603. << FixItHint::CreateInsertion(E->getLocStart(), "&");
  6604. // Check to see if '()' fixit should be emitted.
  6605. QualType ReturnType;
  6606. UnresolvedSet<4> NonTemplateOverloads;
  6607. tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
  6608. if (ReturnType.isNull())
  6609. return;
  6610. if (IsCompare) {
  6611. // There are two cases here. If there is null constant, the only suggest
  6612. // for a pointer return type. If the null is 0, then suggest if the return
  6613. // type is a pointer or an integer type.
  6614. if (!ReturnType->isPointerType()) {
  6615. if (NullKind == Expr::NPCK_ZeroExpression ||
  6616. NullKind == Expr::NPCK_ZeroLiteral) {
  6617. if (!ReturnType->isIntegerType())
  6618. return;
  6619. } else {
  6620. return;
  6621. }
  6622. }
  6623. } else { // !IsCompare
  6624. // For function to bool, only suggest if the function pointer has bool
  6625. // return type.
  6626. if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  6627. return;
  6628. }
  6629. Diag(E->getExprLoc(), diag::note_function_to_function_call)
  6630. << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
  6631. }
  6632. /// Diagnoses "dangerous" implicit conversions within the given
  6633. /// expression (which is a full expression). Implements -Wconversion
  6634. /// and -Wsign-compare.
  6635. ///
  6636. /// \param CC the "context" location of the implicit conversion, i.e.
  6637. /// the most location of the syntactic entity requiring the implicit
  6638. /// conversion
  6639. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  6640. // Don't diagnose in unevaluated contexts.
  6641. if (isUnevaluatedContext())
  6642. return;
  6643. // Don't diagnose for value- or type-dependent expressions.
  6644. if (E->isTypeDependent() || E->isValueDependent())
  6645. return;
  6646. // Check for array bounds violations in cases where the check isn't triggered
  6647. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  6648. // ArraySubscriptExpr is on the RHS of a variable initialization.
  6649. CheckArrayAccess(E);
  6650. // This is not the right CC for (e.g.) a variable initialization.
  6651. AnalyzeImplicitConversions(*this, E, CC);
  6652. }
  6653. /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
  6654. /// Input argument E is a logical expression.
  6655. void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
  6656. ::CheckBoolLikeConversion(*this, E, CC);
  6657. }
  6658. /// Diagnose when expression is an integer constant expression and its evaluation
  6659. /// results in integer overflow
  6660. void Sema::CheckForIntOverflow (Expr *E) {
  6661. if (isa<BinaryOperator>(E->IgnoreParenCasts()))
  6662. E->IgnoreParenCasts()->EvaluateForOverflow(Context);
  6663. }
  6664. namespace {
  6665. /// \brief Visitor for expressions which looks for unsequenced operations on the
  6666. /// same object.
  6667. class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
  6668. typedef EvaluatedExprVisitor<SequenceChecker> Base;
  6669. /// \brief A tree of sequenced regions within an expression. Two regions are
  6670. /// unsequenced if one is an ancestor or a descendent of the other. When we
  6671. /// finish processing an expression with sequencing, such as a comma
  6672. /// expression, we fold its tree nodes into its parent, since they are
  6673. /// unsequenced with respect to nodes we will visit later.
  6674. class SequenceTree {
  6675. struct Value {
  6676. explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
  6677. unsigned Parent : 31;
  6678. bool Merged : 1;
  6679. };
  6680. SmallVector<Value, 8> Values;
  6681. public:
  6682. /// \brief A region within an expression which may be sequenced with respect
  6683. /// to some other region.
  6684. class Seq {
  6685. explicit Seq(unsigned N) : Index(N) {}
  6686. unsigned Index;
  6687. friend class SequenceTree;
  6688. public:
  6689. Seq() : Index(0) {}
  6690. };
  6691. SequenceTree() { Values.push_back(Value(0)); }
  6692. Seq root() const { return Seq(0); }
  6693. /// \brief Create a new sequence of operations, which is an unsequenced
  6694. /// subset of \p Parent. This sequence of operations is sequenced with
  6695. /// respect to other children of \p Parent.
  6696. Seq allocate(Seq Parent) {
  6697. Values.push_back(Value(Parent.Index));
  6698. return Seq(Values.size() - 1);
  6699. }
  6700. /// \brief Merge a sequence of operations into its parent.
  6701. void merge(Seq S) {
  6702. Values[S.Index].Merged = true;
  6703. }
  6704. /// \brief Determine whether two operations are unsequenced. This operation
  6705. /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
  6706. /// should have been merged into its parent as appropriate.
  6707. bool isUnsequenced(Seq Cur, Seq Old) {
  6708. unsigned C = representative(Cur.Index);
  6709. unsigned Target = representative(Old.Index);
  6710. while (C >= Target) {
  6711. if (C == Target)
  6712. return true;
  6713. C = Values[C].Parent;
  6714. }
  6715. return false;
  6716. }
  6717. private:
  6718. /// \brief Pick a representative for a sequence.
  6719. unsigned representative(unsigned K) {
  6720. if (Values[K].Merged)
  6721. // Perform path compression as we go.
  6722. return Values[K].Parent = representative(Values[K].Parent);
  6723. return K;
  6724. }
  6725. };
  6726. /// An object for which we can track unsequenced uses.
  6727. typedef NamedDecl *Object;
  6728. /// Different flavors of object usage which we track. We only track the
  6729. /// least-sequenced usage of each kind.
  6730. enum UsageKind {
  6731. /// A read of an object. Multiple unsequenced reads are OK.
  6732. UK_Use,
  6733. /// A modification of an object which is sequenced before the value
  6734. /// computation of the expression, such as ++n in C++.
  6735. UK_ModAsValue,
  6736. /// A modification of an object which is not sequenced before the value
  6737. /// computation of the expression, such as n++.
  6738. UK_ModAsSideEffect,
  6739. UK_Count = UK_ModAsSideEffect + 1
  6740. };
  6741. struct Usage {
  6742. Usage() : Use(nullptr), Seq() {}
  6743. Expr *Use;
  6744. SequenceTree::Seq Seq;
  6745. };
  6746. struct UsageInfo {
  6747. UsageInfo() : Diagnosed(false) {}
  6748. Usage Uses[UK_Count];
  6749. /// Have we issued a diagnostic for this variable already?
  6750. bool Diagnosed;
  6751. };
  6752. typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
  6753. Sema &SemaRef;
  6754. /// Sequenced regions within the expression.
  6755. SequenceTree Tree;
  6756. /// Declaration modifications and references which we have seen.
  6757. UsageInfoMap UsageMap;
  6758. /// The region we are currently within.
  6759. SequenceTree::Seq Region;
  6760. /// Filled in with declarations which were modified as a side-effect
  6761. /// (that is, post-increment operations).
  6762. SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
  6763. /// Expressions to check later. We defer checking these to reduce
  6764. /// stack usage.
  6765. SmallVectorImpl<Expr *> &WorkList;
  6766. /// RAII object wrapping the visitation of a sequenced subexpression of an
  6767. /// expression. At the end of this process, the side-effects of the evaluation
  6768. /// become sequenced with respect to the value computation of the result, so
  6769. /// we downgrade any UK_ModAsSideEffect within the evaluation to
  6770. /// UK_ModAsValue.
  6771. struct SequencedSubexpression {
  6772. SequencedSubexpression(SequenceChecker &Self)
  6773. : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
  6774. Self.ModAsSideEffect = &ModAsSideEffect;
  6775. }
  6776. ~SequencedSubexpression() {
  6777. for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
  6778. MI != ME; ++MI) {
  6779. UsageInfo &U = Self.UsageMap[MI->first];
  6780. auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
  6781. Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
  6782. SideEffectUsage = MI->second;
  6783. }
  6784. Self.ModAsSideEffect = OldModAsSideEffect;
  6785. }
  6786. SequenceChecker &Self;
  6787. SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
  6788. SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
  6789. };
  6790. /// RAII object wrapping the visitation of a subexpression which we might
  6791. /// choose to evaluate as a constant. If any subexpression is evaluated and
  6792. /// found to be non-constant, this allows us to suppress the evaluation of
  6793. /// the outer expression.
  6794. class EvaluationTracker {
  6795. public:
  6796. EvaluationTracker(SequenceChecker &Self)
  6797. : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
  6798. Self.EvalTracker = this;
  6799. }
  6800. ~EvaluationTracker() {
  6801. Self.EvalTracker = Prev;
  6802. if (Prev)
  6803. Prev->EvalOK &= EvalOK;
  6804. }
  6805. bool evaluate(const Expr *E, bool &Result) {
  6806. if (!EvalOK || E->isValueDependent())
  6807. return false;
  6808. EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
  6809. return EvalOK;
  6810. }
  6811. private:
  6812. SequenceChecker &Self;
  6813. EvaluationTracker *Prev;
  6814. bool EvalOK;
  6815. } *EvalTracker;
  6816. /// \brief Find the object which is produced by the specified expression,
  6817. /// if any.
  6818. Object getObject(Expr *E, bool Mod) const {
  6819. E = E->IgnoreParenCasts();
  6820. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  6821. if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
  6822. return getObject(UO->getSubExpr(), Mod);
  6823. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  6824. if (BO->getOpcode() == BO_Comma)
  6825. return getObject(BO->getRHS(), Mod);
  6826. if (Mod && BO->isAssignmentOp())
  6827. return getObject(BO->getLHS(), Mod);
  6828. } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  6829. // FIXME: Check for more interesting cases, like "x.n = ++x.n".
  6830. if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
  6831. return ME->getMemberDecl();
  6832. } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  6833. // FIXME: If this is a reference, map through to its value.
  6834. return DRE->getDecl();
  6835. return nullptr;
  6836. }
  6837. /// \brief Note that an object was modified or used by an expression.
  6838. void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
  6839. Usage &U = UI.Uses[UK];
  6840. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
  6841. if (UK == UK_ModAsSideEffect && ModAsSideEffect)
  6842. ModAsSideEffect->push_back(std::make_pair(O, U));
  6843. U.Use = Ref;
  6844. U.Seq = Region;
  6845. }
  6846. }
  6847. /// \brief Check whether a modification or use conflicts with a prior usage.
  6848. void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
  6849. bool IsModMod) {
  6850. if (UI.Diagnosed)
  6851. return;
  6852. const Usage &U = UI.Uses[OtherKind];
  6853. if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
  6854. return;
  6855. Expr *Mod = U.Use;
  6856. Expr *ModOrUse = Ref;
  6857. if (OtherKind == UK_Use)
  6858. std::swap(Mod, ModOrUse);
  6859. SemaRef.Diag(Mod->getExprLoc(),
  6860. IsModMod ? diag::warn_unsequenced_mod_mod
  6861. : diag::warn_unsequenced_mod_use)
  6862. << O << SourceRange(ModOrUse->getExprLoc());
  6863. UI.Diagnosed = true;
  6864. }
  6865. void notePreUse(Object O, Expr *Use) {
  6866. UsageInfo &U = UsageMap[O];
  6867. // Uses conflict with other modifications.
  6868. checkUsage(O, U, Use, UK_ModAsValue, false);
  6869. }
  6870. void notePostUse(Object O, Expr *Use) {
  6871. UsageInfo &U = UsageMap[O];
  6872. checkUsage(O, U, Use, UK_ModAsSideEffect, false);
  6873. addUsage(U, O, Use, UK_Use);
  6874. }
  6875. void notePreMod(Object O, Expr *Mod) {
  6876. UsageInfo &U = UsageMap[O];
  6877. // Modifications conflict with other modifications and with uses.
  6878. checkUsage(O, U, Mod, UK_ModAsValue, true);
  6879. checkUsage(O, U, Mod, UK_Use, false);
  6880. }
  6881. void notePostMod(Object O, Expr *Use, UsageKind UK) {
  6882. UsageInfo &U = UsageMap[O];
  6883. checkUsage(O, U, Use, UK_ModAsSideEffect, true);
  6884. addUsage(U, O, Use, UK);
  6885. }
  6886. public:
  6887. SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
  6888. : Base(S.Context), SemaRef(S), Region(Tree.root()),
  6889. ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
  6890. Visit(E);
  6891. }
  6892. void VisitStmt(Stmt *S) {
  6893. // Skip all statements which aren't expressions for now.
  6894. }
  6895. void VisitExpr(Expr *E) {
  6896. // By default, just recurse to evaluated subexpressions.
  6897. Base::VisitStmt(E);
  6898. }
  6899. void VisitCastExpr(CastExpr *E) {
  6900. Object O = Object();
  6901. if (E->getCastKind() == CK_LValueToRValue)
  6902. O = getObject(E->getSubExpr(), false);
  6903. if (O)
  6904. notePreUse(O, E);
  6905. VisitExpr(E);
  6906. if (O)
  6907. notePostUse(O, E);
  6908. }
  6909. void VisitBinComma(BinaryOperator *BO) {
  6910. // C++11 [expr.comma]p1:
  6911. // Every value computation and side effect associated with the left
  6912. // expression is sequenced before every value computation and side
  6913. // effect associated with the right expression.
  6914. SequenceTree::Seq LHS = Tree.allocate(Region);
  6915. SequenceTree::Seq RHS = Tree.allocate(Region);
  6916. SequenceTree::Seq OldRegion = Region;
  6917. {
  6918. SequencedSubexpression SeqLHS(*this);
  6919. Region = LHS;
  6920. Visit(BO->getLHS());
  6921. }
  6922. Region = RHS;
  6923. Visit(BO->getRHS());
  6924. Region = OldRegion;
  6925. // Forget that LHS and RHS are sequenced. They are both unsequenced
  6926. // with respect to other stuff.
  6927. Tree.merge(LHS);
  6928. Tree.merge(RHS);
  6929. }
  6930. void VisitBinAssign(BinaryOperator *BO) {
  6931. // The modification is sequenced after the value computation of the LHS
  6932. // and RHS, so check it before inspecting the operands and update the
  6933. // map afterwards.
  6934. Object O = getObject(BO->getLHS(), true);
  6935. if (!O)
  6936. return VisitExpr(BO);
  6937. notePreMod(O, BO);
  6938. // C++11 [expr.ass]p7:
  6939. // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
  6940. // only once.
  6941. //
  6942. // Therefore, for a compound assignment operator, O is considered used
  6943. // everywhere except within the evaluation of E1 itself.
  6944. if (isa<CompoundAssignOperator>(BO))
  6945. notePreUse(O, BO);
  6946. Visit(BO->getLHS());
  6947. if (isa<CompoundAssignOperator>(BO))
  6948. notePostUse(O, BO);
  6949. Visit(BO->getRHS());
  6950. // C++11 [expr.ass]p1:
  6951. // the assignment is sequenced [...] before the value computation of the
  6952. // assignment expression.
  6953. // C11 6.5.16/3 has no such rule.
  6954. notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  6955. : UK_ModAsSideEffect);
  6956. }
  6957. void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
  6958. VisitBinAssign(CAO);
  6959. }
  6960. void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  6961. void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
  6962. void VisitUnaryPreIncDec(UnaryOperator *UO) {
  6963. Object O = getObject(UO->getSubExpr(), true);
  6964. if (!O)
  6965. return VisitExpr(UO);
  6966. notePreMod(O, UO);
  6967. Visit(UO->getSubExpr());
  6968. // C++11 [expr.pre.incr]p1:
  6969. // the expression ++x is equivalent to x+=1
  6970. notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
  6971. : UK_ModAsSideEffect);
  6972. }
  6973. void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  6974. void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
  6975. void VisitUnaryPostIncDec(UnaryOperator *UO) {
  6976. Object O = getObject(UO->getSubExpr(), true);
  6977. if (!O)
  6978. return VisitExpr(UO);
  6979. notePreMod(O, UO);
  6980. Visit(UO->getSubExpr());
  6981. notePostMod(O, UO, UK_ModAsSideEffect);
  6982. }
  6983. /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
  6984. void VisitBinLOr(BinaryOperator *BO) {
  6985. // The side-effects of the LHS of an '&&' are sequenced before the
  6986. // value computation of the RHS, and hence before the value computation
  6987. // of the '&&' itself, unless the LHS evaluates to zero. We treat them
  6988. // as if they were unconditionally sequenced.
  6989. EvaluationTracker Eval(*this);
  6990. {
  6991. SequencedSubexpression Sequenced(*this);
  6992. Visit(BO->getLHS());
  6993. }
  6994. bool Result;
  6995. if (Eval.evaluate(BO->getLHS(), Result)) {
  6996. if (!Result)
  6997. Visit(BO->getRHS());
  6998. } else {
  6999. // Check for unsequenced operations in the RHS, treating it as an
  7000. // entirely separate evaluation.
  7001. //
  7002. // FIXME: If there are operations in the RHS which are unsequenced
  7003. // with respect to operations outside the RHS, and those operations
  7004. // are unconditionally evaluated, diagnose them.
  7005. WorkList.push_back(BO->getRHS());
  7006. }
  7007. }
  7008. void VisitBinLAnd(BinaryOperator *BO) {
  7009. EvaluationTracker Eval(*this);
  7010. {
  7011. SequencedSubexpression Sequenced(*this);
  7012. Visit(BO->getLHS());
  7013. }
  7014. bool Result;
  7015. if (Eval.evaluate(BO->getLHS(), Result)) {
  7016. if (Result)
  7017. Visit(BO->getRHS());
  7018. } else {
  7019. WorkList.push_back(BO->getRHS());
  7020. }
  7021. }
  7022. // Only visit the condition, unless we can be sure which subexpression will
  7023. // be chosen.
  7024. void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
  7025. EvaluationTracker Eval(*this);
  7026. {
  7027. SequencedSubexpression Sequenced(*this);
  7028. Visit(CO->getCond());
  7029. }
  7030. bool Result;
  7031. if (Eval.evaluate(CO->getCond(), Result))
  7032. Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
  7033. else {
  7034. WorkList.push_back(CO->getTrueExpr());
  7035. WorkList.push_back(CO->getFalseExpr());
  7036. }
  7037. }
  7038. void VisitCallExpr(CallExpr *CE) {
  7039. // C++11 [intro.execution]p15:
  7040. // When calling a function [...], every value computation and side effect
  7041. // associated with any argument expression, or with the postfix expression
  7042. // designating the called function, is sequenced before execution of every
  7043. // expression or statement in the body of the function [and thus before
  7044. // the value computation of its result].
  7045. SequencedSubexpression Sequenced(*this);
  7046. Base::VisitCallExpr(CE);
  7047. // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
  7048. }
  7049. void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
  7050. // This is a call, so all subexpressions are sequenced before the result.
  7051. SequencedSubexpression Sequenced(*this);
  7052. if (!CCE->isListInitialization())
  7053. return VisitExpr(CCE);
  7054. // In C++11, list initializations are sequenced.
  7055. SmallVector<SequenceTree::Seq, 32> Elts;
  7056. SequenceTree::Seq Parent = Region;
  7057. for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
  7058. E = CCE->arg_end();
  7059. I != E; ++I) {
  7060. Region = Tree.allocate(Parent);
  7061. Elts.push_back(Region);
  7062. Visit(*I);
  7063. }
  7064. // Forget that the initializers are sequenced.
  7065. Region = Parent;
  7066. for (unsigned I = 0; I < Elts.size(); ++I)
  7067. Tree.merge(Elts[I]);
  7068. }
  7069. void VisitInitListExpr(InitListExpr *ILE) {
  7070. if (!SemaRef.getLangOpts().CPlusPlus11)
  7071. return VisitExpr(ILE);
  7072. // In C++11, list initializations are sequenced.
  7073. SmallVector<SequenceTree::Seq, 32> Elts;
  7074. SequenceTree::Seq Parent = Region;
  7075. for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
  7076. Expr *E = ILE->getInit(I);
  7077. if (!E) continue;
  7078. Region = Tree.allocate(Parent);
  7079. Elts.push_back(Region);
  7080. Visit(E);
  7081. }
  7082. // Forget that the initializers are sequenced.
  7083. Region = Parent;
  7084. for (unsigned I = 0; I < Elts.size(); ++I)
  7085. Tree.merge(Elts[I]);
  7086. }
  7087. };
  7088. }
  7089. void Sema::CheckUnsequencedOperations(Expr *E) {
  7090. SmallVector<Expr *, 8> WorkList;
  7091. WorkList.push_back(E);
  7092. while (!WorkList.empty()) {
  7093. Expr *Item = WorkList.pop_back_val();
  7094. SequenceChecker(*this, Item, WorkList);
  7095. }
  7096. }
  7097. void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
  7098. bool IsConstexpr) {
  7099. CheckImplicitConversions(E, CheckLoc);
  7100. CheckUnsequencedOperations(E);
  7101. if (!IsConstexpr && !E->isValueDependent())
  7102. CheckForIntOverflow(E);
  7103. }
  7104. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  7105. FieldDecl *BitField,
  7106. Expr *Init) {
  7107. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  7108. }
  7109. static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
  7110. SourceLocation Loc) {
  7111. if (!PType->isVariablyModifiedType())
  7112. return;
  7113. if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
  7114. diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
  7115. return;
  7116. }
  7117. if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
  7118. diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
  7119. return;
  7120. }
  7121. if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
  7122. diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
  7123. return;
  7124. }
  7125. const ArrayType *AT = S.Context.getAsArrayType(PType);
  7126. if (!AT)
  7127. return;
  7128. if (AT->getSizeModifier() != ArrayType::Star) {
  7129. diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
  7130. return;
  7131. }
  7132. S.Diag(Loc, diag::err_array_star_in_function_definition);
  7133. }
  7134. /// CheckParmsForFunctionDef - Check that the parameters of the given
  7135. /// function are appropriate for the definition of a function. This
  7136. /// takes care of any checks that cannot be performed on the
  7137. /// declaration itself, e.g., that the types of each of the function
  7138. /// parameters are complete.
  7139. bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
  7140. ParmVarDecl *const *PEnd,
  7141. bool CheckParameterNames) {
  7142. bool HasInvalidParm = false;
  7143. for (; P != PEnd; ++P) {
  7144. ParmVarDecl *Param = *P;
  7145. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  7146. // function declarator that is part of a function definition of
  7147. // that function shall not have incomplete type.
  7148. //
  7149. // This is also C++ [dcl.fct]p6.
  7150. if (!Param->isInvalidDecl() &&
  7151. !(getLangOpts().HLSL && Param->getType()->isIncompleteArrayType()) && // HLSL Change: allow incomplete array type
  7152. RequireCompleteType(Param->getLocation(), Param->getType(),
  7153. diag::err_typecheck_decl_incomplete_type)) {
  7154. Param->setInvalidDecl();
  7155. HasInvalidParm = true;
  7156. }
  7157. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  7158. // declaration of each parameter shall include an identifier.
  7159. if (CheckParameterNames &&
  7160. Param->getIdentifier() == nullptr &&
  7161. !Param->isImplicit() &&
  7162. !getLangOpts().CPlusPlus)
  7163. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  7164. // C99 6.7.5.3p12:
  7165. // If the function declarator is not part of a definition of that
  7166. // function, parameters may have incomplete type and may use the [*]
  7167. // notation in their sequences of declarator specifiers to specify
  7168. // variable length array types.
  7169. QualType PType = Param->getOriginalType();
  7170. // FIXME: This diagnostic should point the '[*]' if source-location
  7171. // information is added for it.
  7172. diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
  7173. // MSVC destroys objects passed by value in the callee. Therefore a
  7174. // function definition which takes such a parameter must be able to call the
  7175. // object's destructor. However, we don't perform any direct access check
  7176. // on the dtor.
  7177. if (getLangOpts().CPlusPlus && Context.getTargetInfo()
  7178. .getCXXABI()
  7179. .areArgsDestroyedLeftToRightInCallee()) {
  7180. if (!Param->isInvalidDecl()) {
  7181. if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
  7182. CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  7183. if (!ClassDecl->isInvalidDecl() &&
  7184. !ClassDecl->hasIrrelevantDestructor() &&
  7185. !ClassDecl->isDependentContext()) {
  7186. CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
  7187. MarkFunctionReferenced(Param->getLocation(), Destructor);
  7188. DiagnoseUseOfDecl(Destructor, Param->getLocation());
  7189. }
  7190. }
  7191. }
  7192. }
  7193. }
  7194. return HasInvalidParm;
  7195. }
  7196. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  7197. /// pointer cast increases the alignment requirements.
  7198. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  7199. // This is actually a lot of work to potentially be doing on every
  7200. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  7201. if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
  7202. return;
  7203. // Ignore dependent types.
  7204. if (T->isDependentType() || Op->getType()->isDependentType())
  7205. return;
  7206. // Require that the destination be a pointer type.
  7207. const PointerType *DestPtr = T->getAs<PointerType>();
  7208. if (!DestPtr) return;
  7209. // If the destination has alignment 1, we're done.
  7210. QualType DestPointee = DestPtr->getPointeeType();
  7211. if (DestPointee->isIncompleteType()) return;
  7212. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  7213. if (DestAlign.isOne()) return;
  7214. // Require that the source be a pointer type.
  7215. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  7216. if (!SrcPtr) return;
  7217. QualType SrcPointee = SrcPtr->getPointeeType();
  7218. // Whitelist casts from cv void*. We already implicitly
  7219. // whitelisted casts to cv void*, since they have alignment 1.
  7220. // Also whitelist casts involving incomplete types, which implicitly
  7221. // includes 'void'.
  7222. if (SrcPointee->isIncompleteType()) return;
  7223. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  7224. if (SrcAlign >= DestAlign) return;
  7225. Diag(TRange.getBegin(), diag::warn_cast_align)
  7226. << Op->getType() << T
  7227. << static_cast<unsigned>(SrcAlign.getQuantity())
  7228. << static_cast<unsigned>(DestAlign.getQuantity())
  7229. << TRange << Op->getSourceRange();
  7230. }
  7231. static const Type* getElementType(const Expr *BaseExpr) {
  7232. const Type* EltType = BaseExpr->getType().getTypePtr();
  7233. if (EltType->isAnyPointerType())
  7234. return EltType->getPointeeType().getTypePtr();
  7235. else if (EltType->isArrayType())
  7236. return EltType->getBaseElementTypeUnsafe();
  7237. return EltType;
  7238. }
  7239. /// \brief Check whether this array fits the idiom of a size-one tail padded
  7240. /// array member of a struct.
  7241. ///
  7242. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  7243. /// commonly used to emulate flexible arrays in C89 code.
  7244. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  7245. const NamedDecl *ND) {
  7246. if (Size != 1 || !ND) return false;
  7247. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  7248. if (!FD) return false;
  7249. // Don't consider sizes resulting from macro expansions or template argument
  7250. // substitution to form C89 tail-padded arrays.
  7251. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  7252. while (TInfo) {
  7253. TypeLoc TL = TInfo->getTypeLoc();
  7254. // Look through typedefs.
  7255. if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
  7256. const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
  7257. TInfo = TDL->getTypeSourceInfo();
  7258. continue;
  7259. }
  7260. if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
  7261. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  7262. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  7263. return false;
  7264. }
  7265. break;
  7266. }
  7267. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  7268. if (!RD) return false;
  7269. if (RD->isUnion()) return false;
  7270. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  7271. if (!CRD->isStandardLayout()) return false;
  7272. }
  7273. // See if this is the last field decl in the record.
  7274. const Decl *D = FD;
  7275. while ((D = D->getNextDeclInContext()))
  7276. if (isa<FieldDecl>(D))
  7277. return false;
  7278. return true;
  7279. }
  7280. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  7281. const ArraySubscriptExpr *ASE,
  7282. bool AllowOnePastEnd, bool IndexNegated) {
  7283. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  7284. if (IndexExpr->isValueDependent())
  7285. return;
  7286. const Type *EffectiveType = getElementType(BaseExpr);
  7287. BaseExpr = BaseExpr->IgnoreParenCasts();
  7288. const ConstantArrayType *ArrayTy =
  7289. Context.getAsConstantArrayType(BaseExpr->getType());
  7290. if (!ArrayTy)
  7291. return;
  7292. llvm::APSInt index;
  7293. if (!IndexExpr->EvaluateAsInt(index, Context))
  7294. return;
  7295. if (IndexNegated)
  7296. index = -index;
  7297. const NamedDecl *ND = nullptr;
  7298. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  7299. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  7300. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  7301. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  7302. if (index.isUnsigned() || !index.isNegative()) {
  7303. llvm::APInt size = ArrayTy->getSize();
  7304. if (!size.isStrictlyPositive())
  7305. return;
  7306. const Type* BaseType = getElementType(BaseExpr);
  7307. if (BaseType != EffectiveType) {
  7308. // Make sure we're comparing apples to apples when comparing index to size
  7309. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  7310. uint64_t array_typesize = Context.getTypeSize(BaseType);
  7311. // Handle ptrarith_typesize being zero, such as when casting to void*
  7312. if (!ptrarith_typesize) ptrarith_typesize = 1;
  7313. if (ptrarith_typesize != array_typesize) {
  7314. // There's a cast to a different size type involved
  7315. uint64_t ratio = array_typesize / ptrarith_typesize;
  7316. // TODO: Be smarter about handling cases where array_typesize is not a
  7317. // multiple of ptrarith_typesize
  7318. if (ptrarith_typesize * ratio == array_typesize)
  7319. size *= llvm::APInt(size.getBitWidth(), ratio);
  7320. }
  7321. }
  7322. if (size.getBitWidth() > index.getBitWidth())
  7323. index = index.zext(size.getBitWidth());
  7324. else if (size.getBitWidth() < index.getBitWidth())
  7325. size = size.zext(index.getBitWidth());
  7326. // For array subscripting the index must be less than size, but for pointer
  7327. // arithmetic also allow the index (offset) to be equal to size since
  7328. // computing the next address after the end of the array is legal and
  7329. // commonly done e.g. in C++ iterators and range-based for loops.
  7330. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  7331. return;
  7332. // Also don't warn for arrays of size 1 which are members of some
  7333. // structure. These are often used to approximate flexible arrays in C89
  7334. // code.
  7335. if (IsTailPaddedMemberArray(*this, size, ND))
  7336. return;
  7337. // Suppress the warning if the subscript expression (as identified by the
  7338. // ']' location) and the index expression are both from macro expansions
  7339. // within a system header.
  7340. if (ASE) {
  7341. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  7342. ASE->getRBracketLoc());
  7343. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  7344. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  7345. IndexExpr->getLocStart());
  7346. if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
  7347. return;
  7348. }
  7349. }
  7350. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  7351. if (ASE)
  7352. DiagID = diag::warn_array_index_exceeds_bounds;
  7353. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  7354. PDiag(DiagID) << index.toString(10, true)
  7355. << size.toString(10, true)
  7356. << (unsigned)size.getLimitedValue(~0U)
  7357. << IndexExpr->getSourceRange());
  7358. } else {
  7359. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  7360. if (!ASE) {
  7361. DiagID = diag::warn_ptr_arith_precedes_bounds;
  7362. if (index.isNegative()) index = -index;
  7363. }
  7364. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  7365. PDiag(DiagID) << index.toString(10, true)
  7366. << IndexExpr->getSourceRange());
  7367. }
  7368. if (!ND) {
  7369. // Try harder to find a NamedDecl to point at in the note.
  7370. while (const ArraySubscriptExpr *ASE =
  7371. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  7372. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  7373. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  7374. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  7375. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  7376. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  7377. }
  7378. if (ND)
  7379. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  7380. PDiag(diag::note_array_index_out_of_bounds)
  7381. << ND->getDeclName());
  7382. }
  7383. void Sema::CheckArrayAccess(const Expr *expr) {
  7384. int AllowOnePastEnd = 0;
  7385. while (expr) {
  7386. expr = expr->IgnoreParenImpCasts();
  7387. switch (expr->getStmtClass()) {
  7388. case Stmt::ArraySubscriptExprClass: {
  7389. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  7390. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  7391. AllowOnePastEnd > 0);
  7392. return;
  7393. }
  7394. case Stmt::UnaryOperatorClass: {
  7395. // Only unwrap the * and & unary operators
  7396. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  7397. expr = UO->getSubExpr();
  7398. switch (UO->getOpcode()) {
  7399. case UO_AddrOf:
  7400. AllowOnePastEnd++;
  7401. break;
  7402. case UO_Deref:
  7403. AllowOnePastEnd--;
  7404. break;
  7405. default:
  7406. return;
  7407. }
  7408. break;
  7409. }
  7410. case Stmt::ConditionalOperatorClass: {
  7411. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  7412. if (const Expr *lhs = cond->getLHS())
  7413. CheckArrayAccess(lhs);
  7414. if (const Expr *rhs = cond->getRHS())
  7415. CheckArrayAccess(rhs);
  7416. return;
  7417. }
  7418. // HLSL Change Starts : Access checking for HLSL vector and matrix array subscript
  7419. case Stmt::CXXOperatorCallExprClass : {
  7420. if (getLangOpts().HLSL) {
  7421. CheckHLSLArrayAccess(expr);
  7422. }
  7423. return;
  7424. }
  7425. // HLSL Change Ends
  7426. default:
  7427. return;
  7428. }
  7429. }
  7430. }
  7431. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  7432. namespace {
  7433. struct RetainCycleOwner {
  7434. RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
  7435. VarDecl *Variable;
  7436. SourceRange Range;
  7437. SourceLocation Loc;
  7438. bool Indirect;
  7439. void setLocsFrom(Expr *e) {
  7440. Loc = e->getExprLoc();
  7441. Range = e->getSourceRange();
  7442. }
  7443. };
  7444. }
  7445. #if 0 // HLSL Change Starts
  7446. /// Consider whether capturing the given variable can possibly lead to
  7447. /// a retain cycle.
  7448. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  7449. // In ARC, it's captured strongly iff the variable has __strong
  7450. // lifetime. In MRR, it's captured strongly if the variable is
  7451. // __block and has an appropriate type.
  7452. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  7453. return false;
  7454. owner.Variable = var;
  7455. if (ref)
  7456. owner.setLocsFrom(ref);
  7457. return true;
  7458. }
  7459. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  7460. while (true) {
  7461. e = e->IgnoreParens();
  7462. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  7463. switch (cast->getCastKind()) {
  7464. case CK_BitCast:
  7465. case CK_LValueBitCast:
  7466. case CK_LValueToRValue:
  7467. case CK_ARCReclaimReturnedObject:
  7468. e = cast->getSubExpr();
  7469. continue;
  7470. default:
  7471. return false;
  7472. }
  7473. }
  7474. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  7475. ObjCIvarDecl *ivar = ref->getDecl();
  7476. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  7477. return false;
  7478. // Try to find a retain cycle in the base.
  7479. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  7480. return false;
  7481. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  7482. owner.Indirect = true;
  7483. return true;
  7484. }
  7485. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  7486. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  7487. if (!var) return false;
  7488. return considerVariable(var, ref, owner);
  7489. }
  7490. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  7491. if (member->isArrow()) return false;
  7492. // Don't count this as an indirect ownership.
  7493. e = member->getBase();
  7494. continue;
  7495. }
  7496. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  7497. // Only pay attention to pseudo-objects on property references.
  7498. ObjCPropertyRefExpr *pre
  7499. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  7500. ->IgnoreParens());
  7501. if (!pre) return false;
  7502. if (pre->isImplicitProperty()) return false;
  7503. ObjCPropertyDecl *property = pre->getExplicitProperty();
  7504. if (!property->isRetaining() &&
  7505. !(property->getPropertyIvarDecl() &&
  7506. property->getPropertyIvarDecl()->getType()
  7507. .getObjCLifetime() == Qualifiers::OCL_Strong))
  7508. return false;
  7509. owner.Indirect = true;
  7510. if (pre->isSuperReceiver()) {
  7511. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  7512. if (!owner.Variable)
  7513. return false;
  7514. owner.Loc = pre->getLocation();
  7515. owner.Range = pre->getSourceRange();
  7516. return true;
  7517. }
  7518. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  7519. ->getSourceExpr());
  7520. continue;
  7521. }
  7522. // Array ivars?
  7523. return false;
  7524. }
  7525. }
  7526. #endif // HLSL Change Ends
  7527. namespace {
  7528. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  7529. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  7530. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  7531. Context(Context), Variable(variable), Capturer(nullptr),
  7532. VarWillBeReased(false) {}
  7533. ASTContext &Context;
  7534. VarDecl *Variable;
  7535. Expr *Capturer;
  7536. bool VarWillBeReased;
  7537. void VisitDeclRefExpr(DeclRefExpr *ref) {
  7538. if (ref->getDecl() == Variable && !Capturer)
  7539. Capturer = ref;
  7540. }
  7541. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  7542. if (Capturer) return;
  7543. Visit(ref->getBase());
  7544. if (Capturer && ref->isFreeIvar())
  7545. Capturer = ref;
  7546. }
  7547. void VisitBlockExpr(BlockExpr *block) {
  7548. // Look inside nested blocks
  7549. if (block->getBlockDecl()->capturesVariable(Variable))
  7550. Visit(block->getBlockDecl()->getBody());
  7551. }
  7552. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  7553. if (Capturer) return;
  7554. if (OVE->getSourceExpr())
  7555. Visit(OVE->getSourceExpr());
  7556. }
  7557. void VisitBinaryOperator(BinaryOperator *BinOp) {
  7558. if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
  7559. return;
  7560. Expr *LHS = BinOp->getLHS();
  7561. if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
  7562. if (DRE->getDecl() != Variable)
  7563. return;
  7564. if (Expr *RHS = BinOp->getRHS()) {
  7565. RHS = RHS->IgnoreParenCasts();
  7566. llvm::APSInt Value;
  7567. VarWillBeReased =
  7568. (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
  7569. }
  7570. }
  7571. }
  7572. };
  7573. }
  7574. #if 0 // HLSL Change Starts
  7575. /// Check whether the given argument is a block which captures a
  7576. /// variable.
  7577. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  7578. assert(owner.Variable && owner.Loc.isValid());
  7579. e = e->IgnoreParenCasts();
  7580. // Look through [^{...} copy] and Block_copy(^{...}).
  7581. if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
  7582. Selector Cmd = ME->getSelector();
  7583. if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
  7584. e = ME->getInstanceReceiver();
  7585. if (!e)
  7586. return nullptr;
  7587. e = e->IgnoreParenCasts();
  7588. }
  7589. } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
  7590. if (CE->getNumArgs() == 1) {
  7591. FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
  7592. if (Fn) {
  7593. const IdentifierInfo *FnI = Fn->getIdentifier();
  7594. if (FnI && FnI->isStr("_Block_copy")) {
  7595. e = CE->getArg(0)->IgnoreParenCasts();
  7596. }
  7597. }
  7598. }
  7599. }
  7600. BlockExpr *block = dyn_cast<BlockExpr>(e);
  7601. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  7602. return nullptr;
  7603. FindCaptureVisitor visitor(S.Context, owner.Variable);
  7604. visitor.Visit(block->getBlockDecl()->getBody());
  7605. return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
  7606. }
  7607. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  7608. RetainCycleOwner &owner) {
  7609. assert(capturer);
  7610. assert(owner.Variable && owner.Loc.isValid());
  7611. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  7612. << owner.Variable << capturer->getSourceRange();
  7613. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  7614. << owner.Indirect << owner.Range;
  7615. }
  7616. /// Check for a keyword selector that starts with the word 'add' or
  7617. /// 'set'.
  7618. static bool isSetterLikeSelector(Selector sel) {
  7619. if (sel.isUnarySelector()) return false;
  7620. StringRef str = sel.getNameForSlot(0);
  7621. while (!str.empty() && str.front() == '_') str = str.substr(1);
  7622. if (str.startswith("set"))
  7623. str = str.substr(3);
  7624. else if (str.startswith("add")) {
  7625. // Specially whitelist 'addOperationWithBlock:'.
  7626. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  7627. return false;
  7628. str = str.substr(3);
  7629. }
  7630. else
  7631. return false;
  7632. if (str.empty()) return true;
  7633. return !isLowercase(str.front());
  7634. }
  7635. static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
  7636. ObjCMessageExpr *Message) {
  7637. bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
  7638. Message->getReceiverInterface(),
  7639. NSAPI::ClassId_NSMutableArray);
  7640. if (!IsMutableArray) {
  7641. return None;
  7642. }
  7643. Selector Sel = Message->getSelector();
  7644. Optional<NSAPI::NSArrayMethodKind> MKOpt =
  7645. S.NSAPIObj->getNSArrayMethodKind(Sel);
  7646. if (!MKOpt) {
  7647. return None;
  7648. }
  7649. NSAPI::NSArrayMethodKind MK = *MKOpt;
  7650. switch (MK) {
  7651. case NSAPI::NSMutableArr_addObject:
  7652. case NSAPI::NSMutableArr_insertObjectAtIndex:
  7653. case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
  7654. return 0;
  7655. case NSAPI::NSMutableArr_replaceObjectAtIndex:
  7656. return 1;
  7657. default:
  7658. return None;
  7659. }
  7660. return None;
  7661. }
  7662. static
  7663. Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
  7664. ObjCMessageExpr *Message) {
  7665. bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
  7666. Message->getReceiverInterface(),
  7667. NSAPI::ClassId_NSMutableDictionary);
  7668. if (!IsMutableDictionary) {
  7669. return None;
  7670. }
  7671. Selector Sel = Message->getSelector();
  7672. Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
  7673. S.NSAPIObj->getNSDictionaryMethodKind(Sel);
  7674. if (!MKOpt) {
  7675. return None;
  7676. }
  7677. NSAPI::NSDictionaryMethodKind MK = *MKOpt;
  7678. switch (MK) {
  7679. case NSAPI::NSMutableDict_setObjectForKey:
  7680. case NSAPI::NSMutableDict_setValueForKey:
  7681. case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
  7682. return 0;
  7683. default:
  7684. return None;
  7685. }
  7686. return None;
  7687. }
  7688. static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
  7689. bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
  7690. Message->getReceiverInterface(),
  7691. NSAPI::ClassId_NSMutableSet);
  7692. bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
  7693. Message->getReceiverInterface(),
  7694. NSAPI::ClassId_NSMutableOrderedSet);
  7695. if (!IsMutableSet && !IsMutableOrderedSet) {
  7696. return None;
  7697. }
  7698. Selector Sel = Message->getSelector();
  7699. Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
  7700. if (!MKOpt) {
  7701. return None;
  7702. }
  7703. NSAPI::NSSetMethodKind MK = *MKOpt;
  7704. switch (MK) {
  7705. case NSAPI::NSMutableSet_addObject:
  7706. case NSAPI::NSOrderedSet_setObjectAtIndex:
  7707. case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
  7708. case NSAPI::NSOrderedSet_insertObjectAtIndex:
  7709. return 0;
  7710. case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
  7711. return 1;
  7712. }
  7713. return None;
  7714. }
  7715. void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
  7716. if (!Message->isInstanceMessage()) {
  7717. return;
  7718. }
  7719. Optional<int> ArgOpt;
  7720. if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
  7721. !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
  7722. !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
  7723. return;
  7724. }
  7725. int ArgIndex = *ArgOpt;
  7726. Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
  7727. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
  7728. Arg = OE->getSourceExpr()->IgnoreImpCasts();
  7729. }
  7730. if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
  7731. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  7732. if (ArgRE->isObjCSelfExpr()) {
  7733. Diag(Message->getSourceRange().getBegin(),
  7734. diag::warn_objc_circular_container)
  7735. << ArgRE->getDecl()->getName() << StringRef("super");
  7736. }
  7737. }
  7738. } else {
  7739. Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
  7740. if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
  7741. Receiver = OE->getSourceExpr()->IgnoreImpCasts();
  7742. }
  7743. if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
  7744. if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
  7745. if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
  7746. ValueDecl *Decl = ReceiverRE->getDecl();
  7747. Diag(Message->getSourceRange().getBegin(),
  7748. diag::warn_objc_circular_container)
  7749. << Decl->getName() << Decl->getName();
  7750. if (!ArgRE->isObjCSelfExpr()) {
  7751. Diag(Decl->getLocation(),
  7752. diag::note_objc_circular_container_declared_here)
  7753. << Decl->getName();
  7754. }
  7755. }
  7756. }
  7757. } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
  7758. if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
  7759. if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
  7760. ObjCIvarDecl *Decl = IvarRE->getDecl();
  7761. Diag(Message->getSourceRange().getBegin(),
  7762. diag::warn_objc_circular_container)
  7763. << Decl->getName() << Decl->getName();
  7764. Diag(Decl->getLocation(),
  7765. diag::note_objc_circular_container_declared_here)
  7766. << Decl->getName();
  7767. }
  7768. }
  7769. }
  7770. }
  7771. }
  7772. /// Check a message send to see if it's likely to cause a retain cycle.
  7773. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  7774. // Only check instance methods whose selector looks like a setter.
  7775. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  7776. return;
  7777. // Try to find a variable that the receiver is strongly owned by.
  7778. RetainCycleOwner owner;
  7779. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  7780. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  7781. return;
  7782. } else {
  7783. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  7784. owner.Variable = getCurMethodDecl()->getSelfDecl();
  7785. owner.Loc = msg->getSuperLoc();
  7786. owner.Range = msg->getSuperLoc();
  7787. }
  7788. // Check whether the receiver is captured by any of the arguments.
  7789. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  7790. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  7791. return diagnoseRetainCycle(*this, capturer, owner);
  7792. }
  7793. /// Check a property assign to see if it's likely to cause a retain cycle.
  7794. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  7795. RetainCycleOwner owner;
  7796. if (!findRetainCycleOwner(*this, receiver, owner))
  7797. return;
  7798. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  7799. diagnoseRetainCycle(*this, capturer, owner);
  7800. }
  7801. void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
  7802. RetainCycleOwner Owner;
  7803. if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
  7804. return;
  7805. // Because we don't have an expression for the variable, we have to set the
  7806. // location explicitly here.
  7807. Owner.Loc = Var->getLocation();
  7808. Owner.Range = Var->getSourceRange();
  7809. if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
  7810. diagnoseRetainCycle(*this, Capturer, Owner);
  7811. }
  7812. static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
  7813. Expr *RHS, bool isProperty) {
  7814. // Check if RHS is an Objective-C object literal, which also can get
  7815. // immediately zapped in a weak reference. Note that we explicitly
  7816. // allow ObjCStringLiterals, since those are designed to never really die.
  7817. RHS = RHS->IgnoreParenImpCasts();
  7818. // This enum needs to match with the 'select' in
  7819. // warn_objc_arc_literal_assign (off-by-1).
  7820. Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
  7821. if (Kind == Sema::LK_String || Kind == Sema::LK_None)
  7822. return false;
  7823. S.Diag(Loc, diag::warn_arc_literal_assign)
  7824. << (unsigned) Kind
  7825. << (isProperty ? 0 : 1)
  7826. << RHS->getSourceRange();
  7827. return true;
  7828. }
  7829. static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
  7830. Qualifiers::ObjCLifetime LT,
  7831. Expr *RHS, bool isProperty) {
  7832. // Strip off any implicit cast added to get to the one ARC-specific.
  7833. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  7834. if (cast->getCastKind() == CK_ARCConsumeObject) {
  7835. S.Diag(Loc, diag::warn_arc_retained_assign)
  7836. << (LT == Qualifiers::OCL_ExplicitNone)
  7837. << (isProperty ? 0 : 1)
  7838. << RHS->getSourceRange();
  7839. return true;
  7840. }
  7841. RHS = cast->getSubExpr();
  7842. }
  7843. if (LT == Qualifiers::OCL_Weak &&
  7844. checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
  7845. return true;
  7846. return false;
  7847. }
  7848. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  7849. QualType LHS, Expr *RHS) {
  7850. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  7851. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  7852. return false;
  7853. if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
  7854. return true;
  7855. return false;
  7856. }
  7857. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  7858. Expr *LHS, Expr *RHS) {
  7859. QualType LHSType;
  7860. // PropertyRef on LHS type need be directly obtained from
  7861. // its declaration as it has a PseudoType.
  7862. ObjCPropertyRefExpr *PRE
  7863. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  7864. if (PRE && !PRE->isImplicitProperty()) {
  7865. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  7866. if (PD)
  7867. LHSType = PD->getType();
  7868. }
  7869. if (LHSType.isNull())
  7870. LHSType = LHS->getType();
  7871. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  7872. if (LT == Qualifiers::OCL_Weak) {
  7873. if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
  7874. getCurFunction()->markSafeWeakUse(LHS);
  7875. }
  7876. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  7877. return;
  7878. // FIXME. Check for other life times.
  7879. if (LT != Qualifiers::OCL_None)
  7880. return;
  7881. if (PRE) {
  7882. if (PRE->isImplicitProperty())
  7883. return;
  7884. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  7885. if (!PD)
  7886. return;
  7887. unsigned Attributes = PD->getPropertyAttributes();
  7888. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  7889. // when 'assign' attribute was not explicitly specified
  7890. // by user, ignore it and rely on property type itself
  7891. // for lifetime info.
  7892. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  7893. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  7894. LHSType->isObjCRetainableType())
  7895. return;
  7896. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  7897. if (cast->getCastKind() == CK_ARCConsumeObject) {
  7898. Diag(Loc, diag::warn_arc_retained_property_assign)
  7899. << RHS->getSourceRange();
  7900. return;
  7901. }
  7902. RHS = cast->getSubExpr();
  7903. }
  7904. }
  7905. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  7906. if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
  7907. return;
  7908. }
  7909. }
  7910. }
  7911. #endif // HLSL Change
  7912. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  7913. namespace {
  7914. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  7915. SourceLocation StmtLoc,
  7916. const NullStmt *Body) {
  7917. // Do not warn if the body is a macro that expands to nothing, e.g:
  7918. //
  7919. // #define CALL(x)
  7920. // if (condition)
  7921. // CALL(0);
  7922. //
  7923. if (Body->hasLeadingEmptyMacro())
  7924. return false;
  7925. // Get line numbers of statement and body.
  7926. bool StmtLineInvalid;
  7927. unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
  7928. &StmtLineInvalid);
  7929. if (StmtLineInvalid)
  7930. return false;
  7931. bool BodyLineInvalid;
  7932. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  7933. &BodyLineInvalid);
  7934. if (BodyLineInvalid)
  7935. return false;
  7936. // Warn if null statement and body are on the same line.
  7937. if (StmtLine != BodyLine)
  7938. return false;
  7939. return true;
  7940. }
  7941. } // Unnamed namespace
  7942. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  7943. const Stmt *Body,
  7944. unsigned DiagID) {
  7945. // Since this is a syntactic check, don't emit diagnostic for template
  7946. // instantiations, this just adds noise.
  7947. if (CurrentInstantiationScope)
  7948. return;
  7949. // The body should be a null statement.
  7950. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  7951. if (!NBody)
  7952. return;
  7953. // Do the usual checks.
  7954. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  7955. return;
  7956. Diag(NBody->getSemiLoc(), DiagID);
  7957. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  7958. }
  7959. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  7960. const Stmt *PossibleBody) {
  7961. assert(!CurrentInstantiationScope); // Ensured by caller
  7962. SourceLocation StmtLoc;
  7963. const Stmt *Body;
  7964. unsigned DiagID;
  7965. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  7966. StmtLoc = FS->getRParenLoc();
  7967. Body = FS->getBody();
  7968. DiagID = diag::warn_empty_for_body;
  7969. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  7970. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  7971. Body = WS->getBody();
  7972. DiagID = diag::warn_empty_while_body;
  7973. } else
  7974. return; // Neither `for' nor `while'.
  7975. // The body should be a null statement.
  7976. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  7977. if (!NBody)
  7978. return;
  7979. // Skip expensive checks if diagnostic is disabled.
  7980. if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
  7981. return;
  7982. // Do the usual checks.
  7983. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  7984. return;
  7985. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  7986. // noise level low, emit diagnostics only if for/while is followed by a
  7987. // CompoundStmt, e.g.:
  7988. // for (int i = 0; i < n; i++);
  7989. // {
  7990. // a(i);
  7991. // }
  7992. // or if for/while is followed by a statement with more indentation
  7993. // than for/while itself:
  7994. // for (int i = 0; i < n; i++);
  7995. // a(i);
  7996. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  7997. if (!ProbableTypo) {
  7998. bool BodyColInvalid;
  7999. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  8000. PossibleBody->getLocStart(),
  8001. &BodyColInvalid);
  8002. if (BodyColInvalid)
  8003. return;
  8004. bool StmtColInvalid;
  8005. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  8006. S->getLocStart(),
  8007. &StmtColInvalid);
  8008. if (StmtColInvalid)
  8009. return;
  8010. if (BodyCol > StmtCol)
  8011. ProbableTypo = true;
  8012. }
  8013. if (ProbableTypo) {
  8014. Diag(NBody->getSemiLoc(), DiagID);
  8015. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  8016. }
  8017. }
  8018. //===--- CHECK: Warn on self move with std::move. -------------------------===//
  8019. /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
  8020. void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
  8021. SourceLocation OpLoc) {
  8022. if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
  8023. return;
  8024. if (!ActiveTemplateInstantiations.empty())
  8025. return;
  8026. // Strip parens and casts away.
  8027. LHSExpr = LHSExpr->IgnoreParenImpCasts();
  8028. RHSExpr = RHSExpr->IgnoreParenImpCasts();
  8029. // Check for a call expression
  8030. const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
  8031. if (!CE || CE->getNumArgs() != 1)
  8032. return;
  8033. // Check for a call to std::move
  8034. const FunctionDecl *FD = CE->getDirectCallee();
  8035. if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
  8036. !FD->getIdentifier()->isStr("move"))
  8037. return;
  8038. // Get argument from std::move
  8039. RHSExpr = CE->getArg(0);
  8040. const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
  8041. const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
  8042. // Two DeclRefExpr's, check that the decls are the same.
  8043. if (LHSDeclRef && RHSDeclRef) {
  8044. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  8045. return;
  8046. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  8047. RHSDeclRef->getDecl()->getCanonicalDecl())
  8048. return;
  8049. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8050. << LHSExpr->getSourceRange()
  8051. << RHSExpr->getSourceRange();
  8052. return;
  8053. }
  8054. // Member variables require a different approach to check for self moves.
  8055. // MemberExpr's are the same if every nested MemberExpr refers to the same
  8056. // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
  8057. // the base Expr's are CXXThisExpr's.
  8058. const Expr *LHSBase = LHSExpr;
  8059. const Expr *RHSBase = RHSExpr;
  8060. const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
  8061. const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
  8062. if (!LHSME || !RHSME)
  8063. return;
  8064. while (LHSME && RHSME) {
  8065. if (LHSME->getMemberDecl()->getCanonicalDecl() !=
  8066. RHSME->getMemberDecl()->getCanonicalDecl())
  8067. return;
  8068. LHSBase = LHSME->getBase();
  8069. RHSBase = RHSME->getBase();
  8070. LHSME = dyn_cast<MemberExpr>(LHSBase);
  8071. RHSME = dyn_cast<MemberExpr>(RHSBase);
  8072. }
  8073. LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
  8074. RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
  8075. if (LHSDeclRef && RHSDeclRef) {
  8076. if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
  8077. return;
  8078. if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
  8079. RHSDeclRef->getDecl()->getCanonicalDecl())
  8080. return;
  8081. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8082. << LHSExpr->getSourceRange()
  8083. << RHSExpr->getSourceRange();
  8084. return;
  8085. }
  8086. if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
  8087. Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
  8088. << LHSExpr->getSourceRange()
  8089. << RHSExpr->getSourceRange();
  8090. }
  8091. //===--- Layout compatibility ----------------------------------------------//
  8092. namespace {
  8093. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  8094. /// \brief Check if two enumeration types are layout-compatible.
  8095. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  8096. // C++11 [dcl.enum] p8:
  8097. // Two enumeration types are layout-compatible if they have the same
  8098. // underlying type.
  8099. return ED1->isComplete() && ED2->isComplete() &&
  8100. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  8101. }
  8102. /// \brief Check if two fields are layout-compatible.
  8103. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  8104. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  8105. return false;
  8106. if (Field1->isBitField() != Field2->isBitField())
  8107. return false;
  8108. if (Field1->isBitField()) {
  8109. // Make sure that the bit-fields are the same length.
  8110. unsigned Bits1 = Field1->getBitWidthValue(C);
  8111. unsigned Bits2 = Field2->getBitWidthValue(C);
  8112. if (Bits1 != Bits2)
  8113. return false;
  8114. }
  8115. return true;
  8116. }
  8117. /// \brief Check if two standard-layout structs are layout-compatible.
  8118. /// (C++11 [class.mem] p17)
  8119. bool isLayoutCompatibleStruct(ASTContext &C,
  8120. RecordDecl *RD1,
  8121. RecordDecl *RD2) {
  8122. // If both records are C++ classes, check that base classes match.
  8123. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  8124. // If one of records is a CXXRecordDecl we are in C++ mode,
  8125. // thus the other one is a CXXRecordDecl, too.
  8126. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  8127. // Check number of base classes.
  8128. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  8129. return false;
  8130. // Check the base classes.
  8131. for (CXXRecordDecl::base_class_const_iterator
  8132. Base1 = D1CXX->bases_begin(),
  8133. BaseEnd1 = D1CXX->bases_end(),
  8134. Base2 = D2CXX->bases_begin();
  8135. Base1 != BaseEnd1;
  8136. ++Base1, ++Base2) {
  8137. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  8138. return false;
  8139. }
  8140. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  8141. // If only RD2 is a C++ class, it should have zero base classes.
  8142. if (D2CXX->getNumBases() > 0)
  8143. return false;
  8144. }
  8145. // Check the fields.
  8146. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  8147. Field2End = RD2->field_end(),
  8148. Field1 = RD1->field_begin(),
  8149. Field1End = RD1->field_end();
  8150. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  8151. if (!isLayoutCompatible(C, *Field1, *Field2))
  8152. return false;
  8153. }
  8154. if (Field1 != Field1End || Field2 != Field2End)
  8155. return false;
  8156. return true;
  8157. }
  8158. /// \brief Check if two standard-layout unions are layout-compatible.
  8159. /// (C++11 [class.mem] p18)
  8160. bool isLayoutCompatibleUnion(ASTContext &C,
  8161. RecordDecl *RD1,
  8162. RecordDecl *RD2) {
  8163. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  8164. for (auto *Field2 : RD2->fields())
  8165. UnmatchedFields.insert(Field2);
  8166. for (auto *Field1 : RD1->fields()) {
  8167. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  8168. I = UnmatchedFields.begin(),
  8169. E = UnmatchedFields.end();
  8170. for ( ; I != E; ++I) {
  8171. if (isLayoutCompatible(C, Field1, *I)) {
  8172. bool Result = UnmatchedFields.erase(*I);
  8173. (void) Result;
  8174. assert(Result);
  8175. break;
  8176. }
  8177. }
  8178. if (I == E)
  8179. return false;
  8180. }
  8181. return UnmatchedFields.empty();
  8182. }
  8183. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  8184. if (RD1->isUnion() != RD2->isUnion())
  8185. return false;
  8186. if (RD1->isUnion())
  8187. return isLayoutCompatibleUnion(C, RD1, RD2);
  8188. else
  8189. return isLayoutCompatibleStruct(C, RD1, RD2);
  8190. }
  8191. /// \brief Check if two types are layout-compatible in C++11 sense.
  8192. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  8193. if (T1.isNull() || T2.isNull())
  8194. return false;
  8195. // C++11 [basic.types] p11:
  8196. // If two types T1 and T2 are the same type, then T1 and T2 are
  8197. // layout-compatible types.
  8198. if (C.hasSameType(T1, T2))
  8199. return true;
  8200. T1 = T1.getCanonicalType().getUnqualifiedType();
  8201. T2 = T2.getCanonicalType().getUnqualifiedType();
  8202. const Type::TypeClass TC1 = T1->getTypeClass();
  8203. const Type::TypeClass TC2 = T2->getTypeClass();
  8204. if (TC1 != TC2)
  8205. return false;
  8206. if (TC1 == Type::Enum) {
  8207. return isLayoutCompatible(C,
  8208. cast<EnumType>(T1)->getDecl(),
  8209. cast<EnumType>(T2)->getDecl());
  8210. } else if (TC1 == Type::Record) {
  8211. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  8212. return false;
  8213. return isLayoutCompatible(C,
  8214. cast<RecordType>(T1)->getDecl(),
  8215. cast<RecordType>(T2)->getDecl());
  8216. }
  8217. return false;
  8218. }
  8219. }
  8220. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  8221. namespace {
  8222. /// \brief Given a type tag expression find the type tag itself.
  8223. ///
  8224. /// \param TypeExpr Type tag expression, as it appears in user's code.
  8225. ///
  8226. /// \param VD Declaration of an identifier that appears in a type tag.
  8227. ///
  8228. /// \param MagicValue Type tag magic value.
  8229. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  8230. const ValueDecl **VD, uint64_t *MagicValue) {
  8231. while(true) {
  8232. if (!TypeExpr)
  8233. return false;
  8234. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  8235. switch (TypeExpr->getStmtClass()) {
  8236. case Stmt::UnaryOperatorClass: {
  8237. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  8238. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  8239. TypeExpr = UO->getSubExpr();
  8240. continue;
  8241. }
  8242. return false;
  8243. }
  8244. case Stmt::DeclRefExprClass: {
  8245. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  8246. *VD = DRE->getDecl();
  8247. return true;
  8248. }
  8249. case Stmt::IntegerLiteralClass: {
  8250. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  8251. llvm::APInt MagicValueAPInt = IL->getValue();
  8252. if (MagicValueAPInt.getActiveBits() <= 64) {
  8253. *MagicValue = MagicValueAPInt.getZExtValue();
  8254. return true;
  8255. } else
  8256. return false;
  8257. }
  8258. case Stmt::BinaryConditionalOperatorClass:
  8259. case Stmt::ConditionalOperatorClass: {
  8260. const AbstractConditionalOperator *ACO =
  8261. cast<AbstractConditionalOperator>(TypeExpr);
  8262. bool Result;
  8263. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  8264. if (Result)
  8265. TypeExpr = ACO->getTrueExpr();
  8266. else
  8267. TypeExpr = ACO->getFalseExpr();
  8268. continue;
  8269. }
  8270. return false;
  8271. }
  8272. case Stmt::BinaryOperatorClass: {
  8273. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  8274. if (BO->getOpcode() == BO_Comma) {
  8275. TypeExpr = BO->getRHS();
  8276. continue;
  8277. }
  8278. return false;
  8279. }
  8280. default:
  8281. return false;
  8282. }
  8283. }
  8284. }
  8285. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  8286. ///
  8287. /// \param TypeExpr Expression that specifies a type tag.
  8288. ///
  8289. /// \param MagicValues Registered magic values.
  8290. ///
  8291. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  8292. /// kind.
  8293. ///
  8294. /// \param TypeInfo Information about the corresponding C type.
  8295. ///
  8296. /// \returns true if the corresponding C type was found.
  8297. bool GetMatchingCType(
  8298. const IdentifierInfo *ArgumentKind,
  8299. const Expr *TypeExpr, const ASTContext &Ctx,
  8300. const llvm::DenseMap<Sema::TypeTagMagicValue,
  8301. Sema::TypeTagData> *MagicValues,
  8302. bool &FoundWrongKind,
  8303. Sema::TypeTagData &TypeInfo) {
  8304. FoundWrongKind = false;
  8305. // Variable declaration that has type_tag_for_datatype attribute.
  8306. const ValueDecl *VD = nullptr;
  8307. uint64_t MagicValue;
  8308. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  8309. return false;
  8310. if (VD) {
  8311. if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
  8312. if (I->getArgumentKind() != ArgumentKind) {
  8313. FoundWrongKind = true;
  8314. return false;
  8315. }
  8316. TypeInfo.Type = I->getMatchingCType();
  8317. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  8318. TypeInfo.MustBeNull = I->getMustBeNull();
  8319. return true;
  8320. }
  8321. return false;
  8322. }
  8323. if (!MagicValues)
  8324. return false;
  8325. llvm::DenseMap<Sema::TypeTagMagicValue,
  8326. Sema::TypeTagData>::const_iterator I =
  8327. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  8328. if (I == MagicValues->end())
  8329. return false;
  8330. TypeInfo = I->second;
  8331. return true;
  8332. }
  8333. } // unnamed namespace
  8334. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  8335. uint64_t MagicValue, QualType Type,
  8336. bool LayoutCompatible,
  8337. bool MustBeNull) {
  8338. if (!TypeTagForDatatypeMagicValues)
  8339. TypeTagForDatatypeMagicValues.reset(
  8340. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  8341. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  8342. (*TypeTagForDatatypeMagicValues)[Magic] =
  8343. TypeTagData(Type, LayoutCompatible, MustBeNull);
  8344. }
  8345. namespace {
  8346. bool IsSameCharType(QualType T1, QualType T2) {
  8347. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  8348. if (!BT1)
  8349. return false;
  8350. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  8351. if (!BT2)
  8352. return false;
  8353. BuiltinType::Kind T1Kind = BT1->getKind();
  8354. BuiltinType::Kind T2Kind = BT2->getKind();
  8355. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  8356. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  8357. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  8358. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  8359. }
  8360. } // unnamed namespace
  8361. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  8362. const Expr * const *ExprArgs) {
  8363. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  8364. bool IsPointerAttr = Attr->getIsPointer();
  8365. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  8366. bool FoundWrongKind;
  8367. TypeTagData TypeInfo;
  8368. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  8369. TypeTagForDatatypeMagicValues.get(),
  8370. FoundWrongKind, TypeInfo)) {
  8371. if (FoundWrongKind)
  8372. Diag(TypeTagExpr->getExprLoc(),
  8373. diag::warn_type_tag_for_datatype_wrong_kind)
  8374. << TypeTagExpr->getSourceRange();
  8375. return;
  8376. }
  8377. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  8378. if (IsPointerAttr) {
  8379. // Skip implicit cast of pointer to `void *' (as a function argument).
  8380. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  8381. if (ICE->getType()->isVoidPointerType() &&
  8382. ICE->getCastKind() == CK_BitCast)
  8383. ArgumentExpr = ICE->getSubExpr();
  8384. }
  8385. QualType ArgumentType = ArgumentExpr->getType();
  8386. // Passing a `void*' pointer shouldn't trigger a warning.
  8387. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  8388. return;
  8389. if (TypeInfo.MustBeNull) {
  8390. // Type tag with matching void type requires a null pointer.
  8391. if (!ArgumentExpr->isNullPointerConstant(Context,
  8392. Expr::NPC_ValueDependentIsNotNull)) {
  8393. Diag(ArgumentExpr->getExprLoc(),
  8394. diag::warn_type_safety_null_pointer_required)
  8395. << ArgumentKind->getName()
  8396. << ArgumentExpr->getSourceRange()
  8397. << TypeTagExpr->getSourceRange();
  8398. }
  8399. return;
  8400. }
  8401. QualType RequiredType = TypeInfo.Type;
  8402. if (IsPointerAttr)
  8403. RequiredType = Context.getPointerType(RequiredType);
  8404. bool mismatch = false;
  8405. if (!TypeInfo.LayoutCompatible) {
  8406. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  8407. // C++11 [basic.fundamental] p1:
  8408. // Plain char, signed char, and unsigned char are three distinct types.
  8409. //
  8410. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  8411. // char' depending on the current char signedness mode.
  8412. if (mismatch)
  8413. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  8414. RequiredType->getPointeeType())) ||
  8415. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  8416. mismatch = false;
  8417. } else
  8418. if (IsPointerAttr)
  8419. mismatch = !isLayoutCompatible(Context,
  8420. ArgumentType->getPointeeType(),
  8421. RequiredType->getPointeeType());
  8422. else
  8423. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  8424. if (mismatch)
  8425. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  8426. << ArgumentType << ArgumentKind
  8427. << TypeInfo.LayoutCompatible << RequiredType
  8428. << ArgumentExpr->getSourceRange()
  8429. << TypeTagExpr->getSourceRange();
  8430. }