SemaChecking.cpp 217 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887
  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/Initialization.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/ScopeInfo.h"
  20. #include "clang/Analysis/Analyses/FormatString.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/EvaluatedExprVisitor.h"
  29. #include "clang/AST/DeclObjC.h"
  30. #include "clang/AST/StmtCXX.h"
  31. #include "clang/AST/StmtObjC.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "llvm/ADT/BitVector.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "clang/Basic/TargetBuiltins.h"
  38. #include "clang/Basic/TargetInfo.h"
  39. #include "clang/Basic/ConvertUTF.h"
  40. #include <limits>
  41. using namespace clang;
  42. using namespace sema;
  43. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  44. unsigned ByteNo) const {
  45. return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
  46. PP.getLangOpts(), PP.getTargetInfo());
  47. }
  48. /// Checks that a call expression's argument count is the desired number.
  49. /// This is useful when doing custom type-checking. Returns true on error.
  50. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  51. unsigned argCount = call->getNumArgs();
  52. if (argCount == desiredArgCount) return false;
  53. if (argCount < desiredArgCount)
  54. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  55. << 0 /*function call*/ << desiredArgCount << argCount
  56. << call->getSourceRange();
  57. // Highlight all the excess arguments.
  58. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  59. call->getArg(argCount - 1)->getLocEnd());
  60. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  61. << 0 /*function call*/ << desiredArgCount << argCount
  62. << call->getArg(1)->getSourceRange();
  63. }
  64. /// Check that the first argument to __builtin_annotation is an integer
  65. /// and the second argument is a non-wide string literal.
  66. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  67. if (checkArgCount(S, TheCall, 2))
  68. return true;
  69. // First argument should be an integer.
  70. Expr *ValArg = TheCall->getArg(0);
  71. QualType Ty = ValArg->getType();
  72. if (!Ty->isIntegerType()) {
  73. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  74. << ValArg->getSourceRange();
  75. return true;
  76. }
  77. // Second argument should be a constant string.
  78. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  79. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  80. if (!Literal || !Literal->isAscii()) {
  81. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  82. << StrArg->getSourceRange();
  83. return true;
  84. }
  85. TheCall->setType(Ty);
  86. return false;
  87. }
  88. ExprResult
  89. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  90. ExprResult TheCallResult(Owned(TheCall));
  91. // Find out if any arguments are required to be integer constant expressions.
  92. unsigned ICEArguments = 0;
  93. ASTContext::GetBuiltinTypeError Error;
  94. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  95. if (Error != ASTContext::GE_None)
  96. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  97. // If any arguments are required to be ICE's, check and diagnose.
  98. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  99. // Skip arguments not required to be ICE's.
  100. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  101. llvm::APSInt Result;
  102. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  103. return true;
  104. ICEArguments &= ~(1 << ArgNo);
  105. }
  106. switch (BuiltinID) {
  107. case Builtin::BI__builtin___CFStringMakeConstantString:
  108. assert(TheCall->getNumArgs() == 1 &&
  109. "Wrong # arguments to builtin CFStringMakeConstantString");
  110. if (CheckObjCString(TheCall->getArg(0)))
  111. return ExprError();
  112. break;
  113. case Builtin::BI__builtin_stdarg_start:
  114. case Builtin::BI__builtin_va_start:
  115. if (SemaBuiltinVAStart(TheCall))
  116. return ExprError();
  117. break;
  118. case Builtin::BI__builtin_isgreater:
  119. case Builtin::BI__builtin_isgreaterequal:
  120. case Builtin::BI__builtin_isless:
  121. case Builtin::BI__builtin_islessequal:
  122. case Builtin::BI__builtin_islessgreater:
  123. case Builtin::BI__builtin_isunordered:
  124. if (SemaBuiltinUnorderedCompare(TheCall))
  125. return ExprError();
  126. break;
  127. case Builtin::BI__builtin_fpclassify:
  128. if (SemaBuiltinFPClassification(TheCall, 6))
  129. return ExprError();
  130. break;
  131. case Builtin::BI__builtin_isfinite:
  132. case Builtin::BI__builtin_isinf:
  133. case Builtin::BI__builtin_isinf_sign:
  134. case Builtin::BI__builtin_isnan:
  135. case Builtin::BI__builtin_isnormal:
  136. if (SemaBuiltinFPClassification(TheCall, 1))
  137. return ExprError();
  138. break;
  139. case Builtin::BI__builtin_shufflevector:
  140. return SemaBuiltinShuffleVector(TheCall);
  141. // TheCall will be freed by the smart pointer here, but that's fine, since
  142. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  143. case Builtin::BI__builtin_prefetch:
  144. if (SemaBuiltinPrefetch(TheCall))
  145. return ExprError();
  146. break;
  147. case Builtin::BI__builtin_object_size:
  148. if (SemaBuiltinObjectSize(TheCall))
  149. return ExprError();
  150. break;
  151. case Builtin::BI__builtin_longjmp:
  152. if (SemaBuiltinLongjmp(TheCall))
  153. return ExprError();
  154. break;
  155. case Builtin::BI__builtin_classify_type:
  156. if (checkArgCount(*this, TheCall, 1)) return true;
  157. TheCall->setType(Context.IntTy);
  158. break;
  159. case Builtin::BI__builtin_constant_p:
  160. if (checkArgCount(*this, TheCall, 1)) return true;
  161. TheCall->setType(Context.IntTy);
  162. break;
  163. case Builtin::BI__sync_fetch_and_add:
  164. case Builtin::BI__sync_fetch_and_add_1:
  165. case Builtin::BI__sync_fetch_and_add_2:
  166. case Builtin::BI__sync_fetch_and_add_4:
  167. case Builtin::BI__sync_fetch_and_add_8:
  168. case Builtin::BI__sync_fetch_and_add_16:
  169. case Builtin::BI__sync_fetch_and_sub:
  170. case Builtin::BI__sync_fetch_and_sub_1:
  171. case Builtin::BI__sync_fetch_and_sub_2:
  172. case Builtin::BI__sync_fetch_and_sub_4:
  173. case Builtin::BI__sync_fetch_and_sub_8:
  174. case Builtin::BI__sync_fetch_and_sub_16:
  175. case Builtin::BI__sync_fetch_and_or:
  176. case Builtin::BI__sync_fetch_and_or_1:
  177. case Builtin::BI__sync_fetch_and_or_2:
  178. case Builtin::BI__sync_fetch_and_or_4:
  179. case Builtin::BI__sync_fetch_and_or_8:
  180. case Builtin::BI__sync_fetch_and_or_16:
  181. case Builtin::BI__sync_fetch_and_and:
  182. case Builtin::BI__sync_fetch_and_and_1:
  183. case Builtin::BI__sync_fetch_and_and_2:
  184. case Builtin::BI__sync_fetch_and_and_4:
  185. case Builtin::BI__sync_fetch_and_and_8:
  186. case Builtin::BI__sync_fetch_and_and_16:
  187. case Builtin::BI__sync_fetch_and_xor:
  188. case Builtin::BI__sync_fetch_and_xor_1:
  189. case Builtin::BI__sync_fetch_and_xor_2:
  190. case Builtin::BI__sync_fetch_and_xor_4:
  191. case Builtin::BI__sync_fetch_and_xor_8:
  192. case Builtin::BI__sync_fetch_and_xor_16:
  193. case Builtin::BI__sync_add_and_fetch:
  194. case Builtin::BI__sync_add_and_fetch_1:
  195. case Builtin::BI__sync_add_and_fetch_2:
  196. case Builtin::BI__sync_add_and_fetch_4:
  197. case Builtin::BI__sync_add_and_fetch_8:
  198. case Builtin::BI__sync_add_and_fetch_16:
  199. case Builtin::BI__sync_sub_and_fetch:
  200. case Builtin::BI__sync_sub_and_fetch_1:
  201. case Builtin::BI__sync_sub_and_fetch_2:
  202. case Builtin::BI__sync_sub_and_fetch_4:
  203. case Builtin::BI__sync_sub_and_fetch_8:
  204. case Builtin::BI__sync_sub_and_fetch_16:
  205. case Builtin::BI__sync_and_and_fetch:
  206. case Builtin::BI__sync_and_and_fetch_1:
  207. case Builtin::BI__sync_and_and_fetch_2:
  208. case Builtin::BI__sync_and_and_fetch_4:
  209. case Builtin::BI__sync_and_and_fetch_8:
  210. case Builtin::BI__sync_and_and_fetch_16:
  211. case Builtin::BI__sync_or_and_fetch:
  212. case Builtin::BI__sync_or_and_fetch_1:
  213. case Builtin::BI__sync_or_and_fetch_2:
  214. case Builtin::BI__sync_or_and_fetch_4:
  215. case Builtin::BI__sync_or_and_fetch_8:
  216. case Builtin::BI__sync_or_and_fetch_16:
  217. case Builtin::BI__sync_xor_and_fetch:
  218. case Builtin::BI__sync_xor_and_fetch_1:
  219. case Builtin::BI__sync_xor_and_fetch_2:
  220. case Builtin::BI__sync_xor_and_fetch_4:
  221. case Builtin::BI__sync_xor_and_fetch_8:
  222. case Builtin::BI__sync_xor_and_fetch_16:
  223. case Builtin::BI__sync_val_compare_and_swap:
  224. case Builtin::BI__sync_val_compare_and_swap_1:
  225. case Builtin::BI__sync_val_compare_and_swap_2:
  226. case Builtin::BI__sync_val_compare_and_swap_4:
  227. case Builtin::BI__sync_val_compare_and_swap_8:
  228. case Builtin::BI__sync_val_compare_and_swap_16:
  229. case Builtin::BI__sync_bool_compare_and_swap:
  230. case Builtin::BI__sync_bool_compare_and_swap_1:
  231. case Builtin::BI__sync_bool_compare_and_swap_2:
  232. case Builtin::BI__sync_bool_compare_and_swap_4:
  233. case Builtin::BI__sync_bool_compare_and_swap_8:
  234. case Builtin::BI__sync_bool_compare_and_swap_16:
  235. case Builtin::BI__sync_lock_test_and_set:
  236. case Builtin::BI__sync_lock_test_and_set_1:
  237. case Builtin::BI__sync_lock_test_and_set_2:
  238. case Builtin::BI__sync_lock_test_and_set_4:
  239. case Builtin::BI__sync_lock_test_and_set_8:
  240. case Builtin::BI__sync_lock_test_and_set_16:
  241. case Builtin::BI__sync_lock_release:
  242. case Builtin::BI__sync_lock_release_1:
  243. case Builtin::BI__sync_lock_release_2:
  244. case Builtin::BI__sync_lock_release_4:
  245. case Builtin::BI__sync_lock_release_8:
  246. case Builtin::BI__sync_lock_release_16:
  247. case Builtin::BI__sync_swap:
  248. case Builtin::BI__sync_swap_1:
  249. case Builtin::BI__sync_swap_2:
  250. case Builtin::BI__sync_swap_4:
  251. case Builtin::BI__sync_swap_8:
  252. case Builtin::BI__sync_swap_16:
  253. return SemaBuiltinAtomicOverloaded(TheCallResult);
  254. #define BUILTIN(ID, TYPE, ATTRS)
  255. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  256. case Builtin::BI##ID: \
  257. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  258. #include "clang/Basic/Builtins.def"
  259. case Builtin::BI__builtin_annotation:
  260. if (SemaBuiltinAnnotation(*this, TheCall))
  261. return ExprError();
  262. break;
  263. }
  264. // Since the target specific builtins for each arch overlap, only check those
  265. // of the arch we are compiling for.
  266. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  267. switch (Context.getTargetInfo().getTriple().getArch()) {
  268. case llvm::Triple::arm:
  269. case llvm::Triple::thumb:
  270. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  271. return ExprError();
  272. break;
  273. case llvm::Triple::mips:
  274. case llvm::Triple::mipsel:
  275. case llvm::Triple::mips64:
  276. case llvm::Triple::mips64el:
  277. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  278. return ExprError();
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. return TheCallResult;
  285. }
  286. // Get the valid immediate range for the specified NEON type code.
  287. static unsigned RFT(unsigned t, bool shift = false) {
  288. NeonTypeFlags Type(t);
  289. int IsQuad = Type.isQuad();
  290. switch (Type.getEltType()) {
  291. case NeonTypeFlags::Int8:
  292. case NeonTypeFlags::Poly8:
  293. return shift ? 7 : (8 << IsQuad) - 1;
  294. case NeonTypeFlags::Int16:
  295. case NeonTypeFlags::Poly16:
  296. return shift ? 15 : (4 << IsQuad) - 1;
  297. case NeonTypeFlags::Int32:
  298. return shift ? 31 : (2 << IsQuad) - 1;
  299. case NeonTypeFlags::Int64:
  300. return shift ? 63 : (1 << IsQuad) - 1;
  301. case NeonTypeFlags::Float16:
  302. assert(!shift && "cannot shift float types!");
  303. return (4 << IsQuad) - 1;
  304. case NeonTypeFlags::Float32:
  305. assert(!shift && "cannot shift float types!");
  306. return (2 << IsQuad) - 1;
  307. }
  308. llvm_unreachable("Invalid NeonTypeFlag!");
  309. }
  310. /// getNeonEltType - Return the QualType corresponding to the elements of
  311. /// the vector type specified by the NeonTypeFlags. This is used to check
  312. /// the pointer arguments for Neon load/store intrinsics.
  313. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
  314. switch (Flags.getEltType()) {
  315. case NeonTypeFlags::Int8:
  316. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  317. case NeonTypeFlags::Int16:
  318. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  319. case NeonTypeFlags::Int32:
  320. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  321. case NeonTypeFlags::Int64:
  322. return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
  323. case NeonTypeFlags::Poly8:
  324. return Context.SignedCharTy;
  325. case NeonTypeFlags::Poly16:
  326. return Context.ShortTy;
  327. case NeonTypeFlags::Float16:
  328. return Context.UnsignedShortTy;
  329. case NeonTypeFlags::Float32:
  330. return Context.FloatTy;
  331. }
  332. llvm_unreachable("Invalid NeonTypeFlag!");
  333. }
  334. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  335. llvm::APSInt Result;
  336. uint64_t mask = 0;
  337. unsigned TV = 0;
  338. int PtrArgNum = -1;
  339. bool HasConstPtr = false;
  340. switch (BuiltinID) {
  341. #define GET_NEON_OVERLOAD_CHECK
  342. #include "clang/Basic/arm_neon.inc"
  343. #undef GET_NEON_OVERLOAD_CHECK
  344. }
  345. // For NEON intrinsics which are overloaded on vector element type, validate
  346. // the immediate which specifies which variant to emit.
  347. unsigned ImmArg = TheCall->getNumArgs()-1;
  348. if (mask) {
  349. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  350. return true;
  351. TV = Result.getLimitedValue(64);
  352. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  353. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  354. << TheCall->getArg(ImmArg)->getSourceRange();
  355. }
  356. if (PtrArgNum >= 0) {
  357. // Check that pointer arguments have the specified type.
  358. Expr *Arg = TheCall->getArg(PtrArgNum);
  359. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  360. Arg = ICE->getSubExpr();
  361. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  362. QualType RHSTy = RHS.get()->getType();
  363. QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
  364. if (HasConstPtr)
  365. EltTy = EltTy.withConst();
  366. QualType LHSTy = Context.getPointerType(EltTy);
  367. AssignConvertType ConvTy;
  368. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  369. if (RHS.isInvalid())
  370. return true;
  371. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  372. RHS.get(), AA_Assigning))
  373. return true;
  374. }
  375. // For NEON intrinsics which take an immediate value as part of the
  376. // instruction, range check them here.
  377. unsigned i = 0, l = 0, u = 0;
  378. switch (BuiltinID) {
  379. default: return false;
  380. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  381. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  382. case ARM::BI__builtin_arm_vcvtr_f:
  383. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  384. #define GET_NEON_IMMEDIATE_CHECK
  385. #include "clang/Basic/arm_neon.inc"
  386. #undef GET_NEON_IMMEDIATE_CHECK
  387. };
  388. // We can't check the value of a dependent argument.
  389. if (TheCall->getArg(i)->isTypeDependent() ||
  390. TheCall->getArg(i)->isValueDependent())
  391. return false;
  392. // Check that the immediate argument is actually a constant.
  393. if (SemaBuiltinConstantArg(TheCall, i, Result))
  394. return true;
  395. // Range check against the upper/lower values for this isntruction.
  396. unsigned Val = Result.getZExtValue();
  397. if (Val < l || Val > (u + l))
  398. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  399. << l << u+l << TheCall->getArg(i)->getSourceRange();
  400. // FIXME: VFP Intrinsics should error if VFP not present.
  401. return false;
  402. }
  403. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  404. unsigned i = 0, l = 0, u = 0;
  405. switch (BuiltinID) {
  406. default: return false;
  407. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  408. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  409. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  410. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  411. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  412. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  413. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  414. };
  415. // We can't check the value of a dependent argument.
  416. if (TheCall->getArg(i)->isTypeDependent() ||
  417. TheCall->getArg(i)->isValueDependent())
  418. return false;
  419. // Check that the immediate argument is actually a constant.
  420. llvm::APSInt Result;
  421. if (SemaBuiltinConstantArg(TheCall, i, Result))
  422. return true;
  423. // Range check against the upper/lower values for this instruction.
  424. unsigned Val = Result.getZExtValue();
  425. if (Val < l || Val > u)
  426. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  427. << l << u << TheCall->getArg(i)->getSourceRange();
  428. return false;
  429. }
  430. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  431. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  432. /// Returns true when the format fits the function and the FormatStringInfo has
  433. /// been populated.
  434. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  435. FormatStringInfo *FSI) {
  436. FSI->HasVAListArg = Format->getFirstArg() == 0;
  437. FSI->FormatIdx = Format->getFormatIdx() - 1;
  438. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  439. // The way the format attribute works in GCC, the implicit this argument
  440. // of member functions is counted. However, it doesn't appear in our own
  441. // lists, so decrement format_idx in that case.
  442. if (IsCXXMember) {
  443. if(FSI->FormatIdx == 0)
  444. return false;
  445. --FSI->FormatIdx;
  446. if (FSI->FirstDataArg != 0)
  447. --FSI->FirstDataArg;
  448. }
  449. return true;
  450. }
  451. /// Handles the checks for format strings, non-POD arguments to vararg
  452. /// functions, and NULL arguments passed to non-NULL parameters.
  453. void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
  454. unsigned NumArgs,
  455. unsigned NumProtoArgs,
  456. bool IsMemberFunction,
  457. SourceLocation Loc,
  458. SourceRange Range,
  459. VariadicCallType CallType) {
  460. // FIXME: This mechanism should be abstracted to be less fragile and
  461. // more efficient. For example, just map function ids to custom
  462. // handlers.
  463. // Printf and scanf checking.
  464. bool HandledFormatString = false;
  465. for (specific_attr_iterator<FormatAttr>
  466. I = FDecl->specific_attr_begin<FormatAttr>(),
  467. E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
  468. if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
  469. Loc, Range))
  470. HandledFormatString = true;
  471. // Refuse POD arguments that weren't caught by the format string
  472. // checks above.
  473. if (!HandledFormatString && CallType != VariadicDoesNotApply)
  474. for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
  475. variadicArgumentPODCheck(Args[ArgIdx], CallType);
  476. for (specific_attr_iterator<NonNullAttr>
  477. I = FDecl->specific_attr_begin<NonNullAttr>(),
  478. E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
  479. CheckNonNullArguments(*I, Args, Loc);
  480. // Type safety checking.
  481. for (specific_attr_iterator<ArgumentWithTypeTagAttr>
  482. i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
  483. e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
  484. CheckArgumentWithTypeTag(*i, Args);
  485. }
  486. }
  487. /// CheckConstructorCall - Check a constructor call for correctness and safety
  488. /// properties not enforced by the C type system.
  489. void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
  490. unsigned NumArgs,
  491. const FunctionProtoType *Proto,
  492. SourceLocation Loc) {
  493. VariadicCallType CallType =
  494. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  495. checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
  496. /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
  497. }
  498. /// CheckFunctionCall - Check a direct function call for various correctness
  499. /// and safety properties not strictly enforced by the C type system.
  500. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  501. const FunctionProtoType *Proto) {
  502. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
  503. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  504. TheCall->getCallee());
  505. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  506. checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
  507. IsMemberFunction, TheCall->getRParenLoc(),
  508. TheCall->getCallee()->getSourceRange(), CallType);
  509. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  510. // None of the checks below are needed for functions that don't have
  511. // simple names (e.g., C++ conversion functions).
  512. if (!FnInfo)
  513. return false;
  514. unsigned CMId = FDecl->getMemoryFunctionKind();
  515. if (CMId == 0)
  516. return false;
  517. // Handle memory setting and copying functions.
  518. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  519. CheckStrlcpycatArguments(TheCall, FnInfo);
  520. else if (CMId == Builtin::BIstrncat)
  521. CheckStrncatArguments(TheCall, FnInfo);
  522. else
  523. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  524. return false;
  525. }
  526. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  527. Expr **Args, unsigned NumArgs) {
  528. VariadicCallType CallType =
  529. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  530. checkCall(Method, Args, NumArgs, Method->param_size(),
  531. /*IsMemberFunction=*/false,
  532. lbrac, Method->getSourceRange(), CallType);
  533. return false;
  534. }
  535. bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
  536. const FunctionProtoType *Proto) {
  537. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  538. if (!V)
  539. return false;
  540. QualType Ty = V->getType();
  541. if (!Ty->isBlockPointerType())
  542. return false;
  543. VariadicCallType CallType =
  544. Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
  545. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  546. checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
  547. NumProtoArgs, /*IsMemberFunction=*/false,
  548. TheCall->getRParenLoc(),
  549. TheCall->getCallee()->getSourceRange(), CallType);
  550. return false;
  551. }
  552. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  553. AtomicExpr::AtomicOp Op) {
  554. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  555. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  556. // All these operations take one of the following forms:
  557. enum {
  558. // C __c11_atomic_init(A *, C)
  559. Init,
  560. // C __c11_atomic_load(A *, int)
  561. Load,
  562. // void __atomic_load(A *, CP, int)
  563. Copy,
  564. // C __c11_atomic_add(A *, M, int)
  565. Arithmetic,
  566. // C __atomic_exchange_n(A *, CP, int)
  567. Xchg,
  568. // void __atomic_exchange(A *, C *, CP, int)
  569. GNUXchg,
  570. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  571. C11CmpXchg,
  572. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  573. GNUCmpXchg
  574. } Form = Init;
  575. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  576. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  577. // where:
  578. // C is an appropriate type,
  579. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  580. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  581. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  582. // the int parameters are for orderings.
  583. assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  584. AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
  585. && "need to update code for modified C11 atomics");
  586. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  587. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  588. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  589. Op == AtomicExpr::AO__atomic_store_n ||
  590. Op == AtomicExpr::AO__atomic_exchange_n ||
  591. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  592. bool IsAddSub = false;
  593. switch (Op) {
  594. case AtomicExpr::AO__c11_atomic_init:
  595. Form = Init;
  596. break;
  597. case AtomicExpr::AO__c11_atomic_load:
  598. case AtomicExpr::AO__atomic_load_n:
  599. Form = Load;
  600. break;
  601. case AtomicExpr::AO__c11_atomic_store:
  602. case AtomicExpr::AO__atomic_load:
  603. case AtomicExpr::AO__atomic_store:
  604. case AtomicExpr::AO__atomic_store_n:
  605. Form = Copy;
  606. break;
  607. case AtomicExpr::AO__c11_atomic_fetch_add:
  608. case AtomicExpr::AO__c11_atomic_fetch_sub:
  609. case AtomicExpr::AO__atomic_fetch_add:
  610. case AtomicExpr::AO__atomic_fetch_sub:
  611. case AtomicExpr::AO__atomic_add_fetch:
  612. case AtomicExpr::AO__atomic_sub_fetch:
  613. IsAddSub = true;
  614. // Fall through.
  615. case AtomicExpr::AO__c11_atomic_fetch_and:
  616. case AtomicExpr::AO__c11_atomic_fetch_or:
  617. case AtomicExpr::AO__c11_atomic_fetch_xor:
  618. case AtomicExpr::AO__atomic_fetch_and:
  619. case AtomicExpr::AO__atomic_fetch_or:
  620. case AtomicExpr::AO__atomic_fetch_xor:
  621. case AtomicExpr::AO__atomic_fetch_nand:
  622. case AtomicExpr::AO__atomic_and_fetch:
  623. case AtomicExpr::AO__atomic_or_fetch:
  624. case AtomicExpr::AO__atomic_xor_fetch:
  625. case AtomicExpr::AO__atomic_nand_fetch:
  626. Form = Arithmetic;
  627. break;
  628. case AtomicExpr::AO__c11_atomic_exchange:
  629. case AtomicExpr::AO__atomic_exchange_n:
  630. Form = Xchg;
  631. break;
  632. case AtomicExpr::AO__atomic_exchange:
  633. Form = GNUXchg;
  634. break;
  635. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  636. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  637. Form = C11CmpXchg;
  638. break;
  639. case AtomicExpr::AO__atomic_compare_exchange:
  640. case AtomicExpr::AO__atomic_compare_exchange_n:
  641. Form = GNUCmpXchg;
  642. break;
  643. }
  644. // Check we have the right number of arguments.
  645. if (TheCall->getNumArgs() < NumArgs[Form]) {
  646. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  647. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  648. << TheCall->getCallee()->getSourceRange();
  649. return ExprError();
  650. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  651. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  652. diag::err_typecheck_call_too_many_args)
  653. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  654. << TheCall->getCallee()->getSourceRange();
  655. return ExprError();
  656. }
  657. // Inspect the first argument of the atomic operation.
  658. Expr *Ptr = TheCall->getArg(0);
  659. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  660. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  661. if (!pointerType) {
  662. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  663. << Ptr->getType() << Ptr->getSourceRange();
  664. return ExprError();
  665. }
  666. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  667. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  668. QualType ValType = AtomTy; // 'C'
  669. if (IsC11) {
  670. if (!AtomTy->isAtomicType()) {
  671. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  672. << Ptr->getType() << Ptr->getSourceRange();
  673. return ExprError();
  674. }
  675. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  676. }
  677. // For an arithmetic operation, the implied arithmetic must be well-formed.
  678. if (Form == Arithmetic) {
  679. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  680. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  681. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  682. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  683. return ExprError();
  684. }
  685. if (!IsAddSub && !ValType->isIntegerType()) {
  686. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  687. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  688. return ExprError();
  689. }
  690. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  691. // For __atomic_*_n operations, the value type must be a scalar integral or
  692. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  693. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  694. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  695. return ExprError();
  696. }
  697. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
  698. // For GNU atomics, require a trivially-copyable type. This is not part of
  699. // the GNU atomics specification, but we enforce it for sanity.
  700. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  701. << Ptr->getType() << Ptr->getSourceRange();
  702. return ExprError();
  703. }
  704. // FIXME: For any builtin other than a load, the ValType must not be
  705. // const-qualified.
  706. switch (ValType.getObjCLifetime()) {
  707. case Qualifiers::OCL_None:
  708. case Qualifiers::OCL_ExplicitNone:
  709. // okay
  710. break;
  711. case Qualifiers::OCL_Weak:
  712. case Qualifiers::OCL_Strong:
  713. case Qualifiers::OCL_Autoreleasing:
  714. // FIXME: Can this happen? By this point, ValType should be known
  715. // to be trivially copyable.
  716. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  717. << ValType << Ptr->getSourceRange();
  718. return ExprError();
  719. }
  720. QualType ResultType = ValType;
  721. if (Form == Copy || Form == GNUXchg || Form == Init)
  722. ResultType = Context.VoidTy;
  723. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  724. ResultType = Context.BoolTy;
  725. // The type of a parameter passed 'by value'. In the GNU atomics, such
  726. // arguments are actually passed as pointers.
  727. QualType ByValType = ValType; // 'CP'
  728. if (!IsC11 && !IsN)
  729. ByValType = Ptr->getType();
  730. // The first argument --- the pointer --- has a fixed type; we
  731. // deduce the types of the rest of the arguments accordingly. Walk
  732. // the remaining arguments, converting them to the deduced value type.
  733. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  734. QualType Ty;
  735. if (i < NumVals[Form] + 1) {
  736. switch (i) {
  737. case 1:
  738. // The second argument is the non-atomic operand. For arithmetic, this
  739. // is always passed by value, and for a compare_exchange it is always
  740. // passed by address. For the rest, GNU uses by-address and C11 uses
  741. // by-value.
  742. assert(Form != Load);
  743. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  744. Ty = ValType;
  745. else if (Form == Copy || Form == Xchg)
  746. Ty = ByValType;
  747. else if (Form == Arithmetic)
  748. Ty = Context.getPointerDiffType();
  749. else
  750. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  751. break;
  752. case 2:
  753. // The third argument to compare_exchange / GNU exchange is a
  754. // (pointer to a) desired value.
  755. Ty = ByValType;
  756. break;
  757. case 3:
  758. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  759. Ty = Context.BoolTy;
  760. break;
  761. }
  762. } else {
  763. // The order(s) are always converted to int.
  764. Ty = Context.IntTy;
  765. }
  766. InitializedEntity Entity =
  767. InitializedEntity::InitializeParameter(Context, Ty, false);
  768. ExprResult Arg = TheCall->getArg(i);
  769. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  770. if (Arg.isInvalid())
  771. return true;
  772. TheCall->setArg(i, Arg.get());
  773. }
  774. // Permute the arguments into a 'consistent' order.
  775. SmallVector<Expr*, 5> SubExprs;
  776. SubExprs.push_back(Ptr);
  777. switch (Form) {
  778. case Init:
  779. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  780. SubExprs.push_back(TheCall->getArg(1)); // Val1
  781. break;
  782. case Load:
  783. SubExprs.push_back(TheCall->getArg(1)); // Order
  784. break;
  785. case Copy:
  786. case Arithmetic:
  787. case Xchg:
  788. SubExprs.push_back(TheCall->getArg(2)); // Order
  789. SubExprs.push_back(TheCall->getArg(1)); // Val1
  790. break;
  791. case GNUXchg:
  792. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  793. SubExprs.push_back(TheCall->getArg(3)); // Order
  794. SubExprs.push_back(TheCall->getArg(1)); // Val1
  795. SubExprs.push_back(TheCall->getArg(2)); // Val2
  796. break;
  797. case C11CmpXchg:
  798. SubExprs.push_back(TheCall->getArg(3)); // Order
  799. SubExprs.push_back(TheCall->getArg(1)); // Val1
  800. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  801. SubExprs.push_back(TheCall->getArg(2)); // Val2
  802. break;
  803. case GNUCmpXchg:
  804. SubExprs.push_back(TheCall->getArg(4)); // Order
  805. SubExprs.push_back(TheCall->getArg(1)); // Val1
  806. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  807. SubExprs.push_back(TheCall->getArg(2)); // Val2
  808. SubExprs.push_back(TheCall->getArg(3)); // Weak
  809. break;
  810. }
  811. return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  812. SubExprs, ResultType, Op,
  813. TheCall->getRParenLoc()));
  814. }
  815. /// checkBuiltinArgument - Given a call to a builtin function, perform
  816. /// normal type-checking on the given argument, updating the call in
  817. /// place. This is useful when a builtin function requires custom
  818. /// type-checking for some of its arguments but not necessarily all of
  819. /// them.
  820. ///
  821. /// Returns true on error.
  822. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  823. FunctionDecl *Fn = E->getDirectCallee();
  824. assert(Fn && "builtin call without direct callee!");
  825. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  826. InitializedEntity Entity =
  827. InitializedEntity::InitializeParameter(S.Context, Param);
  828. ExprResult Arg = E->getArg(0);
  829. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  830. if (Arg.isInvalid())
  831. return true;
  832. E->setArg(ArgIndex, Arg.take());
  833. return false;
  834. }
  835. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  836. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  837. /// type of its first argument. The main ActOnCallExpr routines have already
  838. /// promoted the types of arguments because all of these calls are prototyped as
  839. /// void(...).
  840. ///
  841. /// This function goes through and does final semantic checking for these
  842. /// builtins,
  843. ExprResult
  844. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  845. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  846. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  847. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  848. // Ensure that we have at least one argument to do type inference from.
  849. if (TheCall->getNumArgs() < 1) {
  850. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  851. << 0 << 1 << TheCall->getNumArgs()
  852. << TheCall->getCallee()->getSourceRange();
  853. return ExprError();
  854. }
  855. // Inspect the first argument of the atomic builtin. This should always be
  856. // a pointer type, whose element is an integral scalar or pointer type.
  857. // Because it is a pointer type, we don't have to worry about any implicit
  858. // casts here.
  859. // FIXME: We don't allow floating point scalars as input.
  860. Expr *FirstArg = TheCall->getArg(0);
  861. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  862. if (FirstArgResult.isInvalid())
  863. return ExprError();
  864. FirstArg = FirstArgResult.take();
  865. TheCall->setArg(0, FirstArg);
  866. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  867. if (!pointerType) {
  868. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  869. << FirstArg->getType() << FirstArg->getSourceRange();
  870. return ExprError();
  871. }
  872. QualType ValType = pointerType->getPointeeType();
  873. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  874. !ValType->isBlockPointerType()) {
  875. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  876. << FirstArg->getType() << FirstArg->getSourceRange();
  877. return ExprError();
  878. }
  879. switch (ValType.getObjCLifetime()) {
  880. case Qualifiers::OCL_None:
  881. case Qualifiers::OCL_ExplicitNone:
  882. // okay
  883. break;
  884. case Qualifiers::OCL_Weak:
  885. case Qualifiers::OCL_Strong:
  886. case Qualifiers::OCL_Autoreleasing:
  887. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  888. << ValType << FirstArg->getSourceRange();
  889. return ExprError();
  890. }
  891. // Strip any qualifiers off ValType.
  892. ValType = ValType.getUnqualifiedType();
  893. // The majority of builtins return a value, but a few have special return
  894. // types, so allow them to override appropriately below.
  895. QualType ResultType = ValType;
  896. // We need to figure out which concrete builtin this maps onto. For example,
  897. // __sync_fetch_and_add with a 2 byte object turns into
  898. // __sync_fetch_and_add_2.
  899. #define BUILTIN_ROW(x) \
  900. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  901. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  902. static const unsigned BuiltinIndices[][5] = {
  903. BUILTIN_ROW(__sync_fetch_and_add),
  904. BUILTIN_ROW(__sync_fetch_and_sub),
  905. BUILTIN_ROW(__sync_fetch_and_or),
  906. BUILTIN_ROW(__sync_fetch_and_and),
  907. BUILTIN_ROW(__sync_fetch_and_xor),
  908. BUILTIN_ROW(__sync_add_and_fetch),
  909. BUILTIN_ROW(__sync_sub_and_fetch),
  910. BUILTIN_ROW(__sync_and_and_fetch),
  911. BUILTIN_ROW(__sync_or_and_fetch),
  912. BUILTIN_ROW(__sync_xor_and_fetch),
  913. BUILTIN_ROW(__sync_val_compare_and_swap),
  914. BUILTIN_ROW(__sync_bool_compare_and_swap),
  915. BUILTIN_ROW(__sync_lock_test_and_set),
  916. BUILTIN_ROW(__sync_lock_release),
  917. BUILTIN_ROW(__sync_swap)
  918. };
  919. #undef BUILTIN_ROW
  920. // Determine the index of the size.
  921. unsigned SizeIndex;
  922. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  923. case 1: SizeIndex = 0; break;
  924. case 2: SizeIndex = 1; break;
  925. case 4: SizeIndex = 2; break;
  926. case 8: SizeIndex = 3; break;
  927. case 16: SizeIndex = 4; break;
  928. default:
  929. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  930. << FirstArg->getType() << FirstArg->getSourceRange();
  931. return ExprError();
  932. }
  933. // Each of these builtins has one pointer argument, followed by some number of
  934. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  935. // that we ignore. Find out which row of BuiltinIndices to read from as well
  936. // as the number of fixed args.
  937. unsigned BuiltinID = FDecl->getBuiltinID();
  938. unsigned BuiltinIndex, NumFixed = 1;
  939. switch (BuiltinID) {
  940. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  941. case Builtin::BI__sync_fetch_and_add:
  942. case Builtin::BI__sync_fetch_and_add_1:
  943. case Builtin::BI__sync_fetch_and_add_2:
  944. case Builtin::BI__sync_fetch_and_add_4:
  945. case Builtin::BI__sync_fetch_and_add_8:
  946. case Builtin::BI__sync_fetch_and_add_16:
  947. BuiltinIndex = 0;
  948. break;
  949. case Builtin::BI__sync_fetch_and_sub:
  950. case Builtin::BI__sync_fetch_and_sub_1:
  951. case Builtin::BI__sync_fetch_and_sub_2:
  952. case Builtin::BI__sync_fetch_and_sub_4:
  953. case Builtin::BI__sync_fetch_and_sub_8:
  954. case Builtin::BI__sync_fetch_and_sub_16:
  955. BuiltinIndex = 1;
  956. break;
  957. case Builtin::BI__sync_fetch_and_or:
  958. case Builtin::BI__sync_fetch_and_or_1:
  959. case Builtin::BI__sync_fetch_and_or_2:
  960. case Builtin::BI__sync_fetch_and_or_4:
  961. case Builtin::BI__sync_fetch_and_or_8:
  962. case Builtin::BI__sync_fetch_and_or_16:
  963. BuiltinIndex = 2;
  964. break;
  965. case Builtin::BI__sync_fetch_and_and:
  966. case Builtin::BI__sync_fetch_and_and_1:
  967. case Builtin::BI__sync_fetch_and_and_2:
  968. case Builtin::BI__sync_fetch_and_and_4:
  969. case Builtin::BI__sync_fetch_and_and_8:
  970. case Builtin::BI__sync_fetch_and_and_16:
  971. BuiltinIndex = 3;
  972. break;
  973. case Builtin::BI__sync_fetch_and_xor:
  974. case Builtin::BI__sync_fetch_and_xor_1:
  975. case Builtin::BI__sync_fetch_and_xor_2:
  976. case Builtin::BI__sync_fetch_and_xor_4:
  977. case Builtin::BI__sync_fetch_and_xor_8:
  978. case Builtin::BI__sync_fetch_and_xor_16:
  979. BuiltinIndex = 4;
  980. break;
  981. case Builtin::BI__sync_add_and_fetch:
  982. case Builtin::BI__sync_add_and_fetch_1:
  983. case Builtin::BI__sync_add_and_fetch_2:
  984. case Builtin::BI__sync_add_and_fetch_4:
  985. case Builtin::BI__sync_add_and_fetch_8:
  986. case Builtin::BI__sync_add_and_fetch_16:
  987. BuiltinIndex = 5;
  988. break;
  989. case Builtin::BI__sync_sub_and_fetch:
  990. case Builtin::BI__sync_sub_and_fetch_1:
  991. case Builtin::BI__sync_sub_and_fetch_2:
  992. case Builtin::BI__sync_sub_and_fetch_4:
  993. case Builtin::BI__sync_sub_and_fetch_8:
  994. case Builtin::BI__sync_sub_and_fetch_16:
  995. BuiltinIndex = 6;
  996. break;
  997. case Builtin::BI__sync_and_and_fetch:
  998. case Builtin::BI__sync_and_and_fetch_1:
  999. case Builtin::BI__sync_and_and_fetch_2:
  1000. case Builtin::BI__sync_and_and_fetch_4:
  1001. case Builtin::BI__sync_and_and_fetch_8:
  1002. case Builtin::BI__sync_and_and_fetch_16:
  1003. BuiltinIndex = 7;
  1004. break;
  1005. case Builtin::BI__sync_or_and_fetch:
  1006. case Builtin::BI__sync_or_and_fetch_1:
  1007. case Builtin::BI__sync_or_and_fetch_2:
  1008. case Builtin::BI__sync_or_and_fetch_4:
  1009. case Builtin::BI__sync_or_and_fetch_8:
  1010. case Builtin::BI__sync_or_and_fetch_16:
  1011. BuiltinIndex = 8;
  1012. break;
  1013. case Builtin::BI__sync_xor_and_fetch:
  1014. case Builtin::BI__sync_xor_and_fetch_1:
  1015. case Builtin::BI__sync_xor_and_fetch_2:
  1016. case Builtin::BI__sync_xor_and_fetch_4:
  1017. case Builtin::BI__sync_xor_and_fetch_8:
  1018. case Builtin::BI__sync_xor_and_fetch_16:
  1019. BuiltinIndex = 9;
  1020. break;
  1021. case Builtin::BI__sync_val_compare_and_swap:
  1022. case Builtin::BI__sync_val_compare_and_swap_1:
  1023. case Builtin::BI__sync_val_compare_and_swap_2:
  1024. case Builtin::BI__sync_val_compare_and_swap_4:
  1025. case Builtin::BI__sync_val_compare_and_swap_8:
  1026. case Builtin::BI__sync_val_compare_and_swap_16:
  1027. BuiltinIndex = 10;
  1028. NumFixed = 2;
  1029. break;
  1030. case Builtin::BI__sync_bool_compare_and_swap:
  1031. case Builtin::BI__sync_bool_compare_and_swap_1:
  1032. case Builtin::BI__sync_bool_compare_and_swap_2:
  1033. case Builtin::BI__sync_bool_compare_and_swap_4:
  1034. case Builtin::BI__sync_bool_compare_and_swap_8:
  1035. case Builtin::BI__sync_bool_compare_and_swap_16:
  1036. BuiltinIndex = 11;
  1037. NumFixed = 2;
  1038. ResultType = Context.BoolTy;
  1039. break;
  1040. case Builtin::BI__sync_lock_test_and_set:
  1041. case Builtin::BI__sync_lock_test_and_set_1:
  1042. case Builtin::BI__sync_lock_test_and_set_2:
  1043. case Builtin::BI__sync_lock_test_and_set_4:
  1044. case Builtin::BI__sync_lock_test_and_set_8:
  1045. case Builtin::BI__sync_lock_test_and_set_16:
  1046. BuiltinIndex = 12;
  1047. break;
  1048. case Builtin::BI__sync_lock_release:
  1049. case Builtin::BI__sync_lock_release_1:
  1050. case Builtin::BI__sync_lock_release_2:
  1051. case Builtin::BI__sync_lock_release_4:
  1052. case Builtin::BI__sync_lock_release_8:
  1053. case Builtin::BI__sync_lock_release_16:
  1054. BuiltinIndex = 13;
  1055. NumFixed = 0;
  1056. ResultType = Context.VoidTy;
  1057. break;
  1058. case Builtin::BI__sync_swap:
  1059. case Builtin::BI__sync_swap_1:
  1060. case Builtin::BI__sync_swap_2:
  1061. case Builtin::BI__sync_swap_4:
  1062. case Builtin::BI__sync_swap_8:
  1063. case Builtin::BI__sync_swap_16:
  1064. BuiltinIndex = 14;
  1065. break;
  1066. }
  1067. // Now that we know how many fixed arguments we expect, first check that we
  1068. // have at least that many.
  1069. if (TheCall->getNumArgs() < 1+NumFixed) {
  1070. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1071. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1072. << TheCall->getCallee()->getSourceRange();
  1073. return ExprError();
  1074. }
  1075. // Get the decl for the concrete builtin from this, we can tell what the
  1076. // concrete integer type we should convert to is.
  1077. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1078. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  1079. IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
  1080. FunctionDecl *NewBuiltinDecl =
  1081. cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
  1082. TUScope, false, DRE->getLocStart()));
  1083. // The first argument --- the pointer --- has a fixed type; we
  1084. // deduce the types of the rest of the arguments accordingly. Walk
  1085. // the remaining arguments, converting them to the deduced value type.
  1086. for (unsigned i = 0; i != NumFixed; ++i) {
  1087. ExprResult Arg = TheCall->getArg(i+1);
  1088. // GCC does an implicit conversion to the pointer or integer ValType. This
  1089. // can fail in some cases (1i -> int**), check for this error case now.
  1090. // Initialize the argument.
  1091. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1092. ValType, /*consume*/ false);
  1093. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1094. if (Arg.isInvalid())
  1095. return ExprError();
  1096. // Okay, we have something that *can* be converted to the right type. Check
  1097. // to see if there is a potentially weird extension going on here. This can
  1098. // happen when you do an atomic operation on something like an char* and
  1099. // pass in 42. The 42 gets converted to char. This is even more strange
  1100. // for things like 45.123 -> char, etc.
  1101. // FIXME: Do this check.
  1102. TheCall->setArg(i+1, Arg.take());
  1103. }
  1104. ASTContext& Context = this->getASTContext();
  1105. // Create a new DeclRefExpr to refer to the new decl.
  1106. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1107. Context,
  1108. DRE->getQualifierLoc(),
  1109. SourceLocation(),
  1110. NewBuiltinDecl,
  1111. /*enclosing*/ false,
  1112. DRE->getLocation(),
  1113. NewBuiltinDecl->getType(),
  1114. DRE->getValueKind());
  1115. // Set the callee in the CallExpr.
  1116. // FIXME: This leaks the original parens and implicit casts.
  1117. ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
  1118. if (PromotedCall.isInvalid())
  1119. return ExprError();
  1120. TheCall->setCallee(PromotedCall.take());
  1121. // Change the result type of the call to match the original value type. This
  1122. // is arbitrary, but the codegen for these builtins ins design to handle it
  1123. // gracefully.
  1124. TheCall->setType(ResultType);
  1125. return TheCallResult;
  1126. }
  1127. /// CheckObjCString - Checks that the argument to the builtin
  1128. /// CFString constructor is correct
  1129. /// Note: It might also make sense to do the UTF-16 conversion here (would
  1130. /// simplify the backend).
  1131. bool Sema::CheckObjCString(Expr *Arg) {
  1132. Arg = Arg->IgnoreParenCasts();
  1133. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  1134. if (!Literal || !Literal->isAscii()) {
  1135. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  1136. << Arg->getSourceRange();
  1137. return true;
  1138. }
  1139. if (Literal->containsNonAsciiOrNull()) {
  1140. StringRef String = Literal->getString();
  1141. unsigned NumBytes = String.size();
  1142. SmallVector<UTF16, 128> ToBuf(NumBytes);
  1143. const UTF8 *FromPtr = (UTF8 *)String.data();
  1144. UTF16 *ToPtr = &ToBuf[0];
  1145. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1146. &ToPtr, ToPtr + NumBytes,
  1147. strictConversion);
  1148. // Check for conversion failure.
  1149. if (Result != conversionOK)
  1150. Diag(Arg->getLocStart(),
  1151. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  1152. }
  1153. return false;
  1154. }
  1155. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  1156. /// Emit an error and return true on failure, return false on success.
  1157. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  1158. Expr *Fn = TheCall->getCallee();
  1159. if (TheCall->getNumArgs() > 2) {
  1160. Diag(TheCall->getArg(2)->getLocStart(),
  1161. diag::err_typecheck_call_too_many_args)
  1162. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1163. << Fn->getSourceRange()
  1164. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1165. (*(TheCall->arg_end()-1))->getLocEnd());
  1166. return true;
  1167. }
  1168. if (TheCall->getNumArgs() < 2) {
  1169. return Diag(TheCall->getLocEnd(),
  1170. diag::err_typecheck_call_too_few_args_at_least)
  1171. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  1172. }
  1173. // Type-check the first argument normally.
  1174. if (checkBuiltinArgument(*this, TheCall, 0))
  1175. return true;
  1176. // Determine whether the current function is variadic or not.
  1177. BlockScopeInfo *CurBlock = getCurBlock();
  1178. bool isVariadic;
  1179. if (CurBlock)
  1180. isVariadic = CurBlock->TheDecl->isVariadic();
  1181. else if (FunctionDecl *FD = getCurFunctionDecl())
  1182. isVariadic = FD->isVariadic();
  1183. else
  1184. isVariadic = getCurMethodDecl()->isVariadic();
  1185. if (!isVariadic) {
  1186. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  1187. return true;
  1188. }
  1189. // Verify that the second argument to the builtin is the last argument of the
  1190. // current function or method.
  1191. bool SecondArgIsLastNamedArgument = false;
  1192. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  1193. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  1194. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  1195. // FIXME: This isn't correct for methods (results in bogus warning).
  1196. // Get the last formal in the current function.
  1197. const ParmVarDecl *LastArg;
  1198. if (CurBlock)
  1199. LastArg = *(CurBlock->TheDecl->param_end()-1);
  1200. else if (FunctionDecl *FD = getCurFunctionDecl())
  1201. LastArg = *(FD->param_end()-1);
  1202. else
  1203. LastArg = *(getCurMethodDecl()->param_end()-1);
  1204. SecondArgIsLastNamedArgument = PV == LastArg;
  1205. }
  1206. }
  1207. if (!SecondArgIsLastNamedArgument)
  1208. Diag(TheCall->getArg(1)->getLocStart(),
  1209. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  1210. return false;
  1211. }
  1212. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  1213. /// friends. This is declared to take (...), so we have to check everything.
  1214. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  1215. if (TheCall->getNumArgs() < 2)
  1216. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1217. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  1218. if (TheCall->getNumArgs() > 2)
  1219. return Diag(TheCall->getArg(2)->getLocStart(),
  1220. diag::err_typecheck_call_too_many_args)
  1221. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1222. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1223. (*(TheCall->arg_end()-1))->getLocEnd());
  1224. ExprResult OrigArg0 = TheCall->getArg(0);
  1225. ExprResult OrigArg1 = TheCall->getArg(1);
  1226. // Do standard promotions between the two arguments, returning their common
  1227. // type.
  1228. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  1229. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  1230. return true;
  1231. // Make sure any conversions are pushed back into the call; this is
  1232. // type safe since unordered compare builtins are declared as "_Bool
  1233. // foo(...)".
  1234. TheCall->setArg(0, OrigArg0.get());
  1235. TheCall->setArg(1, OrigArg1.get());
  1236. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  1237. return false;
  1238. // If the common type isn't a real floating type, then the arguments were
  1239. // invalid for this operation.
  1240. if (Res.isNull() || !Res->isRealFloatingType())
  1241. return Diag(OrigArg0.get()->getLocStart(),
  1242. diag::err_typecheck_call_invalid_ordered_compare)
  1243. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  1244. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  1245. return false;
  1246. }
  1247. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  1248. /// __builtin_isnan and friends. This is declared to take (...), so we have
  1249. /// to check everything. We expect the last argument to be a floating point
  1250. /// value.
  1251. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  1252. if (TheCall->getNumArgs() < NumArgs)
  1253. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1254. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  1255. if (TheCall->getNumArgs() > NumArgs)
  1256. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  1257. diag::err_typecheck_call_too_many_args)
  1258. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  1259. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  1260. (*(TheCall->arg_end()-1))->getLocEnd());
  1261. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  1262. if (OrigArg->isTypeDependent())
  1263. return false;
  1264. // This operation requires a non-_Complex floating-point number.
  1265. if (!OrigArg->getType()->isRealFloatingType())
  1266. return Diag(OrigArg->getLocStart(),
  1267. diag::err_typecheck_call_invalid_unary_fp)
  1268. << OrigArg->getType() << OrigArg->getSourceRange();
  1269. // If this is an implicit conversion from float -> double, remove it.
  1270. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  1271. Expr *CastArg = Cast->getSubExpr();
  1272. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  1273. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  1274. "promotion from float to double is the only expected cast here");
  1275. Cast->setSubExpr(0);
  1276. TheCall->setArg(NumArgs-1, CastArg);
  1277. }
  1278. }
  1279. return false;
  1280. }
  1281. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  1282. // This is declared to take (...), so we have to check everything.
  1283. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  1284. if (TheCall->getNumArgs() < 2)
  1285. return ExprError(Diag(TheCall->getLocEnd(),
  1286. diag::err_typecheck_call_too_few_args_at_least)
  1287. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1288. << TheCall->getSourceRange());
  1289. // Determine which of the following types of shufflevector we're checking:
  1290. // 1) unary, vector mask: (lhs, mask)
  1291. // 2) binary, vector mask: (lhs, rhs, mask)
  1292. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  1293. QualType resType = TheCall->getArg(0)->getType();
  1294. unsigned numElements = 0;
  1295. if (!TheCall->getArg(0)->isTypeDependent() &&
  1296. !TheCall->getArg(1)->isTypeDependent()) {
  1297. QualType LHSType = TheCall->getArg(0)->getType();
  1298. QualType RHSType = TheCall->getArg(1)->getType();
  1299. if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
  1300. Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
  1301. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1302. TheCall->getArg(1)->getLocEnd());
  1303. return ExprError();
  1304. }
  1305. numElements = LHSType->getAs<VectorType>()->getNumElements();
  1306. unsigned numResElements = TheCall->getNumArgs() - 2;
  1307. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  1308. // with mask. If so, verify that RHS is an integer vector type with the
  1309. // same number of elts as lhs.
  1310. if (TheCall->getNumArgs() == 2) {
  1311. if (!RHSType->hasIntegerRepresentation() ||
  1312. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  1313. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1314. << SourceRange(TheCall->getArg(1)->getLocStart(),
  1315. TheCall->getArg(1)->getLocEnd());
  1316. numResElements = numElements;
  1317. }
  1318. else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  1319. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1320. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1321. TheCall->getArg(1)->getLocEnd());
  1322. return ExprError();
  1323. } else if (numElements != numResElements) {
  1324. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  1325. resType = Context.getVectorType(eltType, numResElements,
  1326. VectorType::GenericVector);
  1327. }
  1328. }
  1329. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  1330. if (TheCall->getArg(i)->isTypeDependent() ||
  1331. TheCall->getArg(i)->isValueDependent())
  1332. continue;
  1333. llvm::APSInt Result(32);
  1334. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  1335. return ExprError(Diag(TheCall->getLocStart(),
  1336. diag::err_shufflevector_nonconstant_argument)
  1337. << TheCall->getArg(i)->getSourceRange());
  1338. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  1339. return ExprError(Diag(TheCall->getLocStart(),
  1340. diag::err_shufflevector_argument_too_large)
  1341. << TheCall->getArg(i)->getSourceRange());
  1342. }
  1343. SmallVector<Expr*, 32> exprs;
  1344. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  1345. exprs.push_back(TheCall->getArg(i));
  1346. TheCall->setArg(i, 0);
  1347. }
  1348. return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
  1349. TheCall->getCallee()->getLocStart(),
  1350. TheCall->getRParenLoc()));
  1351. }
  1352. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  1353. // This is declared to take (const void*, ...) and can take two
  1354. // optional constant int args.
  1355. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  1356. unsigned NumArgs = TheCall->getNumArgs();
  1357. if (NumArgs > 3)
  1358. return Diag(TheCall->getLocEnd(),
  1359. diag::err_typecheck_call_too_many_args_at_most)
  1360. << 0 /*function call*/ << 3 << NumArgs
  1361. << TheCall->getSourceRange();
  1362. // Argument 0 is checked for us and the remaining arguments must be
  1363. // constant integers.
  1364. for (unsigned i = 1; i != NumArgs; ++i) {
  1365. Expr *Arg = TheCall->getArg(i);
  1366. // We can't check the value of a dependent argument.
  1367. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1368. continue;
  1369. llvm::APSInt Result;
  1370. if (SemaBuiltinConstantArg(TheCall, i, Result))
  1371. return true;
  1372. // FIXME: gcc issues a warning and rewrites these to 0. These
  1373. // seems especially odd for the third argument since the default
  1374. // is 3.
  1375. if (i == 1) {
  1376. if (Result.getLimitedValue() > 1)
  1377. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1378. << "0" << "1" << Arg->getSourceRange();
  1379. } else {
  1380. if (Result.getLimitedValue() > 3)
  1381. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1382. << "0" << "3" << Arg->getSourceRange();
  1383. }
  1384. }
  1385. return false;
  1386. }
  1387. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  1388. /// TheCall is a constant expression.
  1389. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  1390. llvm::APSInt &Result) {
  1391. Expr *Arg = TheCall->getArg(ArgNum);
  1392. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1393. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1394. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  1395. if (!Arg->isIntegerConstantExpr(Result, Context))
  1396. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  1397. << FDecl->getDeclName() << Arg->getSourceRange();
  1398. return false;
  1399. }
  1400. /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
  1401. /// int type). This simply type checks that type is one of the defined
  1402. /// constants (0-3).
  1403. // For compatibility check 0-3, llvm only handles 0 and 2.
  1404. bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
  1405. llvm::APSInt Result;
  1406. // We can't check the value of a dependent argument.
  1407. if (TheCall->getArg(1)->isTypeDependent() ||
  1408. TheCall->getArg(1)->isValueDependent())
  1409. return false;
  1410. // Check constant-ness first.
  1411. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1412. return true;
  1413. Expr *Arg = TheCall->getArg(1);
  1414. if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
  1415. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1416. << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1417. }
  1418. return false;
  1419. }
  1420. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  1421. /// This checks that val is a constant 1.
  1422. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  1423. Expr *Arg = TheCall->getArg(1);
  1424. llvm::APSInt Result;
  1425. // TODO: This is less than ideal. Overload this to take a value.
  1426. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1427. return true;
  1428. if (Result != 1)
  1429. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  1430. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1431. return false;
  1432. }
  1433. // Determine if an expression is a string literal or constant string.
  1434. // If this function returns false on the arguments to a function expecting a
  1435. // format string, we will usually need to emit a warning.
  1436. // True string literals are then checked by CheckFormatString.
  1437. Sema::StringLiteralCheckType
  1438. Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
  1439. unsigned NumArgs, bool HasVAListArg,
  1440. unsigned format_idx, unsigned firstDataArg,
  1441. FormatStringType Type, VariadicCallType CallType,
  1442. bool inFunctionCall) {
  1443. tryAgain:
  1444. if (E->isTypeDependent() || E->isValueDependent())
  1445. return SLCT_NotALiteral;
  1446. E = E->IgnoreParenCasts();
  1447. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
  1448. // Technically -Wformat-nonliteral does not warn about this case.
  1449. // The behavior of printf and friends in this case is implementation
  1450. // dependent. Ideally if the format string cannot be null then
  1451. // it should have a 'nonnull' attribute in the function prototype.
  1452. return SLCT_CheckedLiteral;
  1453. switch (E->getStmtClass()) {
  1454. case Stmt::BinaryConditionalOperatorClass:
  1455. case Stmt::ConditionalOperatorClass: {
  1456. // The expression is a literal if both sub-expressions were, and it was
  1457. // completely checked only if both sub-expressions were checked.
  1458. const AbstractConditionalOperator *C =
  1459. cast<AbstractConditionalOperator>(E);
  1460. StringLiteralCheckType Left =
  1461. checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
  1462. HasVAListArg, format_idx, firstDataArg,
  1463. Type, CallType, inFunctionCall);
  1464. if (Left == SLCT_NotALiteral)
  1465. return SLCT_NotALiteral;
  1466. StringLiteralCheckType Right =
  1467. checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
  1468. HasVAListArg, format_idx, firstDataArg,
  1469. Type, CallType, inFunctionCall);
  1470. return Left < Right ? Left : Right;
  1471. }
  1472. case Stmt::ImplicitCastExprClass: {
  1473. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  1474. goto tryAgain;
  1475. }
  1476. case Stmt::OpaqueValueExprClass:
  1477. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  1478. E = src;
  1479. goto tryAgain;
  1480. }
  1481. return SLCT_NotALiteral;
  1482. case Stmt::PredefinedExprClass:
  1483. // While __func__, etc., are technically not string literals, they
  1484. // cannot contain format specifiers and thus are not a security
  1485. // liability.
  1486. return SLCT_UncheckedLiteral;
  1487. case Stmt::DeclRefExprClass: {
  1488. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1489. // As an exception, do not flag errors for variables binding to
  1490. // const string literals.
  1491. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1492. bool isConstant = false;
  1493. QualType T = DR->getType();
  1494. if (const ArrayType *AT = Context.getAsArrayType(T)) {
  1495. isConstant = AT->getElementType().isConstant(Context);
  1496. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  1497. isConstant = T.isConstant(Context) &&
  1498. PT->getPointeeType().isConstant(Context);
  1499. } else if (T->isObjCObjectPointerType()) {
  1500. // In ObjC, there is usually no "const ObjectPointer" type,
  1501. // so don't check if the pointee type is constant.
  1502. isConstant = T.isConstant(Context);
  1503. }
  1504. if (isConstant) {
  1505. if (const Expr *Init = VD->getAnyInitializer()) {
  1506. // Look through initializers like const char c[] = { "foo" }
  1507. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  1508. if (InitList->isStringLiteralInit())
  1509. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  1510. }
  1511. return checkFormatStringExpr(Init, Args, NumArgs,
  1512. HasVAListArg, format_idx,
  1513. firstDataArg, Type, CallType,
  1514. /*inFunctionCall*/false);
  1515. }
  1516. }
  1517. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  1518. // special check to see if the format string is a function parameter
  1519. // of the function calling the printf function. If the function
  1520. // has an attribute indicating it is a printf-like function, then we
  1521. // should suppress warnings concerning non-literals being used in a call
  1522. // to a vprintf function. For example:
  1523. //
  1524. // void
  1525. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  1526. // va_list ap;
  1527. // va_start(ap, fmt);
  1528. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  1529. // ...
  1530. //
  1531. if (HasVAListArg) {
  1532. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  1533. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  1534. int PVIndex = PV->getFunctionScopeIndex() + 1;
  1535. for (specific_attr_iterator<FormatAttr>
  1536. i = ND->specific_attr_begin<FormatAttr>(),
  1537. e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  1538. FormatAttr *PVFormat = *i;
  1539. // adjust for implicit parameter
  1540. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1541. if (MD->isInstance())
  1542. ++PVIndex;
  1543. // We also check if the formats are compatible.
  1544. // We can't pass a 'scanf' string to a 'printf' function.
  1545. if (PVIndex == PVFormat->getFormatIdx() &&
  1546. Type == GetFormatStringType(PVFormat))
  1547. return SLCT_UncheckedLiteral;
  1548. }
  1549. }
  1550. }
  1551. }
  1552. }
  1553. return SLCT_NotALiteral;
  1554. }
  1555. case Stmt::CallExprClass:
  1556. case Stmt::CXXMemberCallExprClass: {
  1557. const CallExpr *CE = cast<CallExpr>(E);
  1558. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  1559. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  1560. unsigned ArgIndex = FA->getFormatIdx();
  1561. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1562. if (MD->isInstance())
  1563. --ArgIndex;
  1564. const Expr *Arg = CE->getArg(ArgIndex - 1);
  1565. return checkFormatStringExpr(Arg, Args, NumArgs,
  1566. HasVAListArg, format_idx, firstDataArg,
  1567. Type, CallType, inFunctionCall);
  1568. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1569. unsigned BuiltinID = FD->getBuiltinID();
  1570. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  1571. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  1572. const Expr *Arg = CE->getArg(0);
  1573. return checkFormatStringExpr(Arg, Args, NumArgs,
  1574. HasVAListArg, format_idx,
  1575. firstDataArg, Type, CallType,
  1576. inFunctionCall);
  1577. }
  1578. }
  1579. }
  1580. return SLCT_NotALiteral;
  1581. }
  1582. case Stmt::ObjCStringLiteralClass:
  1583. case Stmt::StringLiteralClass: {
  1584. const StringLiteral *StrE = NULL;
  1585. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  1586. StrE = ObjCFExpr->getString();
  1587. else
  1588. StrE = cast<StringLiteral>(E);
  1589. if (StrE) {
  1590. CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
  1591. firstDataArg, Type, inFunctionCall, CallType);
  1592. return SLCT_CheckedLiteral;
  1593. }
  1594. return SLCT_NotALiteral;
  1595. }
  1596. default:
  1597. return SLCT_NotALiteral;
  1598. }
  1599. }
  1600. void
  1601. Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
  1602. const Expr * const *ExprArgs,
  1603. SourceLocation CallSiteLoc) {
  1604. for (NonNullAttr::args_iterator i = NonNull->args_begin(),
  1605. e = NonNull->args_end();
  1606. i != e; ++i) {
  1607. const Expr *ArgExpr = ExprArgs[*i];
  1608. if (ArgExpr->isNullPointerConstant(Context,
  1609. Expr::NPC_ValueDependentIsNotNull))
  1610. Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1611. }
  1612. }
  1613. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  1614. return llvm::StringSwitch<FormatStringType>(Format->getType())
  1615. .Case("scanf", FST_Scanf)
  1616. .Cases("printf", "printf0", FST_Printf)
  1617. .Cases("NSString", "CFString", FST_NSString)
  1618. .Case("strftime", FST_Strftime)
  1619. .Case("strfmon", FST_Strfmon)
  1620. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  1621. .Default(FST_Unknown);
  1622. }
  1623. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  1624. /// functions) for correct use of format strings.
  1625. /// Returns true if a format string has been fully checked.
  1626. bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
  1627. unsigned NumArgs, bool IsCXXMember,
  1628. VariadicCallType CallType,
  1629. SourceLocation Loc, SourceRange Range) {
  1630. FormatStringInfo FSI;
  1631. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  1632. return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
  1633. FSI.FirstDataArg, GetFormatStringType(Format),
  1634. CallType, Loc, Range);
  1635. return false;
  1636. }
  1637. bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
  1638. bool HasVAListArg, unsigned format_idx,
  1639. unsigned firstDataArg, FormatStringType Type,
  1640. VariadicCallType CallType,
  1641. SourceLocation Loc, SourceRange Range) {
  1642. // CHECK: printf/scanf-like function is called with no format string.
  1643. if (format_idx >= NumArgs) {
  1644. Diag(Loc, diag::warn_missing_format_string) << Range;
  1645. return false;
  1646. }
  1647. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  1648. // CHECK: format string is not a string literal.
  1649. //
  1650. // Dynamically generated format strings are difficult to
  1651. // automatically vet at compile time. Requiring that format strings
  1652. // are string literals: (1) permits the checking of format strings by
  1653. // the compiler and thereby (2) can practically remove the source of
  1654. // many format string exploits.
  1655. // Format string can be either ObjC string (e.g. @"%d") or
  1656. // C string (e.g. "%d")
  1657. // ObjC string uses the same format specifiers as C string, so we can use
  1658. // the same format string checking logic for both ObjC and C strings.
  1659. StringLiteralCheckType CT =
  1660. checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
  1661. format_idx, firstDataArg, Type, CallType);
  1662. if (CT != SLCT_NotALiteral)
  1663. // Literal format string found, check done!
  1664. return CT == SLCT_CheckedLiteral;
  1665. // Strftime is particular as it always uses a single 'time' argument,
  1666. // so it is safe to pass a non-literal string.
  1667. if (Type == FST_Strftime)
  1668. return false;
  1669. // Do not emit diag when the string param is a macro expansion and the
  1670. // format is either NSString or CFString. This is a hack to prevent
  1671. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  1672. // which are usually used in place of NS and CF string literals.
  1673. if (Type == FST_NSString &&
  1674. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  1675. return false;
  1676. // If there are no arguments specified, warn with -Wformat-security, otherwise
  1677. // warn only with -Wformat-nonliteral.
  1678. if (NumArgs == format_idx+1)
  1679. Diag(Args[format_idx]->getLocStart(),
  1680. diag::warn_format_nonliteral_noargs)
  1681. << OrigFormatExpr->getSourceRange();
  1682. else
  1683. Diag(Args[format_idx]->getLocStart(),
  1684. diag::warn_format_nonliteral)
  1685. << OrigFormatExpr->getSourceRange();
  1686. return false;
  1687. }
  1688. namespace {
  1689. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  1690. protected:
  1691. Sema &S;
  1692. const StringLiteral *FExpr;
  1693. const Expr *OrigFormatExpr;
  1694. const unsigned FirstDataArg;
  1695. const unsigned NumDataArgs;
  1696. const char *Beg; // Start of format string.
  1697. const bool HasVAListArg;
  1698. const Expr * const *Args;
  1699. const unsigned NumArgs;
  1700. unsigned FormatIdx;
  1701. llvm::BitVector CoveredArgs;
  1702. bool usesPositionalArgs;
  1703. bool atFirstArg;
  1704. bool inFunctionCall;
  1705. Sema::VariadicCallType CallType;
  1706. public:
  1707. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  1708. const Expr *origFormatExpr, unsigned firstDataArg,
  1709. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  1710. Expr **args, unsigned numArgs,
  1711. unsigned formatIdx, bool inFunctionCall,
  1712. Sema::VariadicCallType callType)
  1713. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  1714. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  1715. Beg(beg), HasVAListArg(hasVAListArg),
  1716. Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
  1717. usesPositionalArgs(false), atFirstArg(true),
  1718. inFunctionCall(inFunctionCall), CallType(callType) {
  1719. CoveredArgs.resize(numDataArgs);
  1720. CoveredArgs.reset();
  1721. }
  1722. void DoneProcessing();
  1723. void HandleIncompleteSpecifier(const char *startSpecifier,
  1724. unsigned specifierLen);
  1725. void HandleNonStandardLengthModifier(
  1726. const analyze_format_string::LengthModifier &LM,
  1727. const char *startSpecifier, unsigned specifierLen);
  1728. void HandleNonStandardConversionSpecifier(
  1729. const analyze_format_string::ConversionSpecifier &CS,
  1730. const char *startSpecifier, unsigned specifierLen);
  1731. void HandleNonStandardConversionSpecification(
  1732. const analyze_format_string::LengthModifier &LM,
  1733. const analyze_format_string::ConversionSpecifier &CS,
  1734. const char *startSpecifier, unsigned specifierLen);
  1735. virtual void HandlePosition(const char *startPos, unsigned posLen);
  1736. virtual void HandleInvalidPosition(const char *startSpecifier,
  1737. unsigned specifierLen,
  1738. analyze_format_string::PositionContext p);
  1739. virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
  1740. void HandleNullChar(const char *nullCharacter);
  1741. template <typename Range>
  1742. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  1743. const Expr *ArgumentExpr,
  1744. PartialDiagnostic PDiag,
  1745. SourceLocation StringLoc,
  1746. bool IsStringLocation, Range StringRange,
  1747. FixItHint Fixit = FixItHint());
  1748. protected:
  1749. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  1750. const char *startSpec,
  1751. unsigned specifierLen,
  1752. const char *csStart, unsigned csLen);
  1753. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1754. const char *startSpec,
  1755. unsigned specifierLen);
  1756. SourceRange getFormatStringRange();
  1757. CharSourceRange getSpecifierRange(const char *startSpecifier,
  1758. unsigned specifierLen);
  1759. SourceLocation getLocationOfByte(const char *x);
  1760. const Expr *getDataArg(unsigned i) const;
  1761. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  1762. const analyze_format_string::ConversionSpecifier &CS,
  1763. const char *startSpecifier, unsigned specifierLen,
  1764. unsigned argIndex);
  1765. template <typename Range>
  1766. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  1767. bool IsStringLocation, Range StringRange,
  1768. FixItHint Fixit = FixItHint());
  1769. void CheckPositionalAndNonpositionalArgs(
  1770. const analyze_format_string::FormatSpecifier *FS);
  1771. };
  1772. }
  1773. SourceRange CheckFormatHandler::getFormatStringRange() {
  1774. return OrigFormatExpr->getSourceRange();
  1775. }
  1776. CharSourceRange CheckFormatHandler::
  1777. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  1778. SourceLocation Start = getLocationOfByte(startSpecifier);
  1779. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  1780. // Advance the end SourceLocation by one due to half-open ranges.
  1781. End = End.getLocWithOffset(1);
  1782. return CharSourceRange::getCharRange(Start, End);
  1783. }
  1784. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  1785. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  1786. }
  1787. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  1788. unsigned specifierLen){
  1789. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  1790. getLocationOfByte(startSpecifier),
  1791. /*IsStringLocation*/true,
  1792. getSpecifierRange(startSpecifier, specifierLen));
  1793. }
  1794. void CheckFormatHandler::HandleNonStandardLengthModifier(
  1795. const analyze_format_string::LengthModifier &LM,
  1796. const char *startSpecifier, unsigned specifierLen) {
  1797. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
  1798. << 0,
  1799. getLocationOfByte(LM.getStart()),
  1800. /*IsStringLocation*/true,
  1801. getSpecifierRange(startSpecifier, specifierLen));
  1802. }
  1803. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  1804. const analyze_format_string::ConversionSpecifier &CS,
  1805. const char *startSpecifier, unsigned specifierLen) {
  1806. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
  1807. << 1,
  1808. getLocationOfByte(CS.getStart()),
  1809. /*IsStringLocation*/true,
  1810. getSpecifierRange(startSpecifier, specifierLen));
  1811. }
  1812. void CheckFormatHandler::HandleNonStandardConversionSpecification(
  1813. const analyze_format_string::LengthModifier &LM,
  1814. const analyze_format_string::ConversionSpecifier &CS,
  1815. const char *startSpecifier, unsigned specifierLen) {
  1816. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
  1817. << LM.toString() << CS.toString(),
  1818. getLocationOfByte(LM.getStart()),
  1819. /*IsStringLocation*/true,
  1820. getSpecifierRange(startSpecifier, specifierLen));
  1821. }
  1822. void CheckFormatHandler::HandlePosition(const char *startPos,
  1823. unsigned posLen) {
  1824. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  1825. getLocationOfByte(startPos),
  1826. /*IsStringLocation*/true,
  1827. getSpecifierRange(startPos, posLen));
  1828. }
  1829. void
  1830. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  1831. analyze_format_string::PositionContext p) {
  1832. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  1833. << (unsigned) p,
  1834. getLocationOfByte(startPos), /*IsStringLocation*/true,
  1835. getSpecifierRange(startPos, posLen));
  1836. }
  1837. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  1838. unsigned posLen) {
  1839. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  1840. getLocationOfByte(startPos),
  1841. /*IsStringLocation*/true,
  1842. getSpecifierRange(startPos, posLen));
  1843. }
  1844. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  1845. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  1846. // The presence of a null character is likely an error.
  1847. EmitFormatDiagnostic(
  1848. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  1849. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  1850. getFormatStringRange());
  1851. }
  1852. }
  1853. // Note that this may return NULL if there was an error parsing or building
  1854. // one of the argument expressions.
  1855. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  1856. return Args[FirstDataArg + i];
  1857. }
  1858. void CheckFormatHandler::DoneProcessing() {
  1859. // Does the number of data arguments exceed the number of
  1860. // format conversions in the format string?
  1861. if (!HasVAListArg) {
  1862. // Find any arguments that weren't covered.
  1863. CoveredArgs.flip();
  1864. signed notCoveredArg = CoveredArgs.find_first();
  1865. if (notCoveredArg >= 0) {
  1866. assert((unsigned)notCoveredArg < NumDataArgs);
  1867. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  1868. SourceLocation Loc = E->getLocStart();
  1869. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  1870. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  1871. Loc, /*IsStringLocation*/false,
  1872. getFormatStringRange());
  1873. }
  1874. }
  1875. }
  1876. }
  1877. }
  1878. bool
  1879. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  1880. SourceLocation Loc,
  1881. const char *startSpec,
  1882. unsigned specifierLen,
  1883. const char *csStart,
  1884. unsigned csLen) {
  1885. bool keepGoing = true;
  1886. if (argIndex < NumDataArgs) {
  1887. // Consider the argument coverered, even though the specifier doesn't
  1888. // make sense.
  1889. CoveredArgs.set(argIndex);
  1890. }
  1891. else {
  1892. // If argIndex exceeds the number of data arguments we
  1893. // don't issue a warning because that is just a cascade of warnings (and
  1894. // they may have intended '%%' anyway). We don't want to continue processing
  1895. // the format string after this point, however, as we will like just get
  1896. // gibberish when trying to match arguments.
  1897. keepGoing = false;
  1898. }
  1899. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  1900. << StringRef(csStart, csLen),
  1901. Loc, /*IsStringLocation*/true,
  1902. getSpecifierRange(startSpec, specifierLen));
  1903. return keepGoing;
  1904. }
  1905. void
  1906. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1907. const char *startSpec,
  1908. unsigned specifierLen) {
  1909. EmitFormatDiagnostic(
  1910. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  1911. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  1912. }
  1913. bool
  1914. CheckFormatHandler::CheckNumArgs(
  1915. const analyze_format_string::FormatSpecifier &FS,
  1916. const analyze_format_string::ConversionSpecifier &CS,
  1917. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  1918. if (argIndex >= NumDataArgs) {
  1919. PartialDiagnostic PDiag = FS.usesPositionalArg()
  1920. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  1921. << (argIndex+1) << NumDataArgs)
  1922. : S.PDiag(diag::warn_printf_insufficient_data_args);
  1923. EmitFormatDiagnostic(
  1924. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  1925. getSpecifierRange(startSpecifier, specifierLen));
  1926. return false;
  1927. }
  1928. return true;
  1929. }
  1930. template<typename Range>
  1931. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  1932. SourceLocation Loc,
  1933. bool IsStringLocation,
  1934. Range StringRange,
  1935. FixItHint FixIt) {
  1936. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  1937. Loc, IsStringLocation, StringRange, FixIt);
  1938. }
  1939. /// \brief If the format string is not within the funcion call, emit a note
  1940. /// so that the function call and string are in diagnostic messages.
  1941. ///
  1942. /// \param InFunctionCall if true, the format string is within the function
  1943. /// call and only one diagnostic message will be produced. Otherwise, an
  1944. /// extra note will be emitted pointing to location of the format string.
  1945. ///
  1946. /// \param ArgumentExpr the expression that is passed as the format string
  1947. /// argument in the function call. Used for getting locations when two
  1948. /// diagnostics are emitted.
  1949. ///
  1950. /// \param PDiag the callee should already have provided any strings for the
  1951. /// diagnostic message. This function only adds locations and fixits
  1952. /// to diagnostics.
  1953. ///
  1954. /// \param Loc primary location for diagnostic. If two diagnostics are
  1955. /// required, one will be at Loc and a new SourceLocation will be created for
  1956. /// the other one.
  1957. ///
  1958. /// \param IsStringLocation if true, Loc points to the format string should be
  1959. /// used for the note. Otherwise, Loc points to the argument list and will
  1960. /// be used with PDiag.
  1961. ///
  1962. /// \param StringRange some or all of the string to highlight. This is
  1963. /// templated so it can accept either a CharSourceRange or a SourceRange.
  1964. ///
  1965. /// \param FixIt optional fix it hint for the format string.
  1966. template<typename Range>
  1967. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  1968. const Expr *ArgumentExpr,
  1969. PartialDiagnostic PDiag,
  1970. SourceLocation Loc,
  1971. bool IsStringLocation,
  1972. Range StringRange,
  1973. FixItHint FixIt) {
  1974. if (InFunctionCall)
  1975. S.Diag(Loc, PDiag) << StringRange << FixIt;
  1976. else {
  1977. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  1978. << ArgumentExpr->getSourceRange();
  1979. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  1980. diag::note_format_string_defined)
  1981. << StringRange << FixIt;
  1982. }
  1983. }
  1984. //===--- CHECK: Printf format string checking ------------------------------===//
  1985. namespace {
  1986. class CheckPrintfHandler : public CheckFormatHandler {
  1987. bool ObjCContext;
  1988. public:
  1989. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  1990. const Expr *origFormatExpr, unsigned firstDataArg,
  1991. unsigned numDataArgs, bool isObjC,
  1992. const char *beg, bool hasVAListArg,
  1993. Expr **Args, unsigned NumArgs,
  1994. unsigned formatIdx, bool inFunctionCall,
  1995. Sema::VariadicCallType CallType)
  1996. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  1997. numDataArgs, beg, hasVAListArg, Args, NumArgs,
  1998. formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
  1999. {}
  2000. bool HandleInvalidPrintfConversionSpecifier(
  2001. const analyze_printf::PrintfSpecifier &FS,
  2002. const char *startSpecifier,
  2003. unsigned specifierLen);
  2004. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  2005. const char *startSpecifier,
  2006. unsigned specifierLen);
  2007. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2008. const char *StartSpecifier,
  2009. unsigned SpecifierLen,
  2010. const Expr *E);
  2011. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  2012. const char *startSpecifier, unsigned specifierLen);
  2013. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  2014. const analyze_printf::OptionalAmount &Amt,
  2015. unsigned type,
  2016. const char *startSpecifier, unsigned specifierLen);
  2017. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2018. const analyze_printf::OptionalFlag &flag,
  2019. const char *startSpecifier, unsigned specifierLen);
  2020. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  2021. const analyze_printf::OptionalFlag &ignoredFlag,
  2022. const analyze_printf::OptionalFlag &flag,
  2023. const char *startSpecifier, unsigned specifierLen);
  2024. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  2025. const Expr *E, const CharSourceRange &CSR);
  2026. };
  2027. }
  2028. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  2029. const analyze_printf::PrintfSpecifier &FS,
  2030. const char *startSpecifier,
  2031. unsigned specifierLen) {
  2032. const analyze_printf::PrintfConversionSpecifier &CS =
  2033. FS.getConversionSpecifier();
  2034. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2035. getLocationOfByte(CS.getStart()),
  2036. startSpecifier, specifierLen,
  2037. CS.getStart(), CS.getLength());
  2038. }
  2039. bool CheckPrintfHandler::HandleAmount(
  2040. const analyze_format_string::OptionalAmount &Amt,
  2041. unsigned k, const char *startSpecifier,
  2042. unsigned specifierLen) {
  2043. if (Amt.hasDataArgument()) {
  2044. if (!HasVAListArg) {
  2045. unsigned argIndex = Amt.getArgIndex();
  2046. if (argIndex >= NumDataArgs) {
  2047. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  2048. << k,
  2049. getLocationOfByte(Amt.getStart()),
  2050. /*IsStringLocation*/true,
  2051. getSpecifierRange(startSpecifier, specifierLen));
  2052. // Don't do any more checking. We will just emit
  2053. // spurious errors.
  2054. return false;
  2055. }
  2056. // Type check the data argument. It should be an 'int'.
  2057. // Although not in conformance with C99, we also allow the argument to be
  2058. // an 'unsigned int' as that is a reasonably safe case. GCC also
  2059. // doesn't emit a warning for that case.
  2060. CoveredArgs.set(argIndex);
  2061. const Expr *Arg = getDataArg(argIndex);
  2062. if (!Arg)
  2063. return false;
  2064. QualType T = Arg->getType();
  2065. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  2066. assert(AT.isValid());
  2067. if (!AT.matchesType(S.Context, T)) {
  2068. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  2069. << k << AT.getRepresentativeTypeName(S.Context)
  2070. << T << Arg->getSourceRange(),
  2071. getLocationOfByte(Amt.getStart()),
  2072. /*IsStringLocation*/true,
  2073. getSpecifierRange(startSpecifier, specifierLen));
  2074. // Don't do any more checking. We will just emit
  2075. // spurious errors.
  2076. return false;
  2077. }
  2078. }
  2079. }
  2080. return true;
  2081. }
  2082. void CheckPrintfHandler::HandleInvalidAmount(
  2083. const analyze_printf::PrintfSpecifier &FS,
  2084. const analyze_printf::OptionalAmount &Amt,
  2085. unsigned type,
  2086. const char *startSpecifier,
  2087. unsigned specifierLen) {
  2088. const analyze_printf::PrintfConversionSpecifier &CS =
  2089. FS.getConversionSpecifier();
  2090. FixItHint fixit =
  2091. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  2092. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  2093. Amt.getConstantLength()))
  2094. : FixItHint();
  2095. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  2096. << type << CS.toString(),
  2097. getLocationOfByte(Amt.getStart()),
  2098. /*IsStringLocation*/true,
  2099. getSpecifierRange(startSpecifier, specifierLen),
  2100. fixit);
  2101. }
  2102. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2103. const analyze_printf::OptionalFlag &flag,
  2104. const char *startSpecifier,
  2105. unsigned specifierLen) {
  2106. // Warn about pointless flag with a fixit removal.
  2107. const analyze_printf::PrintfConversionSpecifier &CS =
  2108. FS.getConversionSpecifier();
  2109. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  2110. << flag.toString() << CS.toString(),
  2111. getLocationOfByte(flag.getPosition()),
  2112. /*IsStringLocation*/true,
  2113. getSpecifierRange(startSpecifier, specifierLen),
  2114. FixItHint::CreateRemoval(
  2115. getSpecifierRange(flag.getPosition(), 1)));
  2116. }
  2117. void CheckPrintfHandler::HandleIgnoredFlag(
  2118. const analyze_printf::PrintfSpecifier &FS,
  2119. const analyze_printf::OptionalFlag &ignoredFlag,
  2120. const analyze_printf::OptionalFlag &flag,
  2121. const char *startSpecifier,
  2122. unsigned specifierLen) {
  2123. // Warn about ignored flag with a fixit removal.
  2124. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  2125. << ignoredFlag.toString() << flag.toString(),
  2126. getLocationOfByte(ignoredFlag.getPosition()),
  2127. /*IsStringLocation*/true,
  2128. getSpecifierRange(startSpecifier, specifierLen),
  2129. FixItHint::CreateRemoval(
  2130. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  2131. }
  2132. // Determines if the specified is a C++ class or struct containing
  2133. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  2134. // "c_str()").
  2135. template<typename MemberKind>
  2136. static llvm::SmallPtrSet<MemberKind*, 1>
  2137. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  2138. const RecordType *RT = Ty->getAs<RecordType>();
  2139. llvm::SmallPtrSet<MemberKind*, 1> Results;
  2140. if (!RT)
  2141. return Results;
  2142. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2143. if (!RD)
  2144. return Results;
  2145. LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
  2146. Sema::LookupMemberName);
  2147. // We just need to include all members of the right kind turned up by the
  2148. // filter, at this point.
  2149. if (S.LookupQualifiedName(R, RT->getDecl()))
  2150. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2151. NamedDecl *decl = (*I)->getUnderlyingDecl();
  2152. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  2153. Results.insert(FK);
  2154. }
  2155. return Results;
  2156. }
  2157. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  2158. // better diagnostic if so. AT is assumed to be valid.
  2159. // Returns true when a c_str() conversion method is found.
  2160. bool CheckPrintfHandler::checkForCStrMembers(
  2161. const analyze_printf::ArgType &AT, const Expr *E,
  2162. const CharSourceRange &CSR) {
  2163. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  2164. MethodSet Results =
  2165. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  2166. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  2167. MI != ME; ++MI) {
  2168. const CXXMethodDecl *Method = *MI;
  2169. if (Method->getNumParams() == 0 &&
  2170. AT.matchesType(S.Context, Method->getResultType())) {
  2171. // FIXME: Suggest parens if the expression needs them.
  2172. SourceLocation EndLoc =
  2173. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
  2174. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  2175. << "c_str()"
  2176. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  2177. return true;
  2178. }
  2179. }
  2180. return false;
  2181. }
  2182. bool
  2183. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  2184. &FS,
  2185. const char *startSpecifier,
  2186. unsigned specifierLen) {
  2187. using namespace analyze_format_string;
  2188. using namespace analyze_printf;
  2189. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  2190. if (FS.consumesDataArgument()) {
  2191. if (atFirstArg) {
  2192. atFirstArg = false;
  2193. usesPositionalArgs = FS.usesPositionalArg();
  2194. }
  2195. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2196. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2197. startSpecifier, specifierLen);
  2198. return false;
  2199. }
  2200. }
  2201. // First check if the field width, precision, and conversion specifier
  2202. // have matching data arguments.
  2203. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  2204. startSpecifier, specifierLen)) {
  2205. return false;
  2206. }
  2207. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  2208. startSpecifier, specifierLen)) {
  2209. return false;
  2210. }
  2211. if (!CS.consumesDataArgument()) {
  2212. // FIXME: Technically specifying a precision or field width here
  2213. // makes no sense. Worth issuing a warning at some point.
  2214. return true;
  2215. }
  2216. // Consume the argument.
  2217. unsigned argIndex = FS.getArgIndex();
  2218. if (argIndex < NumDataArgs) {
  2219. // The check to see if the argIndex is valid will come later.
  2220. // We set the bit here because we may exit early from this
  2221. // function if we encounter some other error.
  2222. CoveredArgs.set(argIndex);
  2223. }
  2224. // Check for using an Objective-C specific conversion specifier
  2225. // in a non-ObjC literal.
  2226. if (!ObjCContext && CS.isObjCArg()) {
  2227. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  2228. specifierLen);
  2229. }
  2230. // Check for invalid use of field width
  2231. if (!FS.hasValidFieldWidth()) {
  2232. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  2233. startSpecifier, specifierLen);
  2234. }
  2235. // Check for invalid use of precision
  2236. if (!FS.hasValidPrecision()) {
  2237. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  2238. startSpecifier, specifierLen);
  2239. }
  2240. // Check each flag does not conflict with any other component.
  2241. if (!FS.hasValidThousandsGroupingPrefix())
  2242. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  2243. if (!FS.hasValidLeadingZeros())
  2244. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  2245. if (!FS.hasValidPlusPrefix())
  2246. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  2247. if (!FS.hasValidSpacePrefix())
  2248. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  2249. if (!FS.hasValidAlternativeForm())
  2250. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  2251. if (!FS.hasValidLeftJustified())
  2252. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  2253. // Check that flags are not ignored by another flag
  2254. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  2255. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  2256. startSpecifier, specifierLen);
  2257. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  2258. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  2259. startSpecifier, specifierLen);
  2260. // Check the length modifier is valid with the given conversion specifier.
  2261. const LengthModifier &LM = FS.getLengthModifier();
  2262. if (!FS.hasValidLengthModifier())
  2263. EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
  2264. << LM.toString() << CS.toString(),
  2265. getLocationOfByte(LM.getStart()),
  2266. /*IsStringLocation*/true,
  2267. getSpecifierRange(startSpecifier, specifierLen),
  2268. FixItHint::CreateRemoval(
  2269. getSpecifierRange(LM.getStart(),
  2270. LM.getLength())));
  2271. if (!FS.hasStandardLengthModifier())
  2272. HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
  2273. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2274. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2275. if (!FS.hasStandardLengthConversionCombination())
  2276. HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
  2277. specifierLen);
  2278. // The remaining checks depend on the data arguments.
  2279. if (HasVAListArg)
  2280. return true;
  2281. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2282. return false;
  2283. const Expr *Arg = getDataArg(argIndex);
  2284. if (!Arg)
  2285. return true;
  2286. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  2287. }
  2288. bool
  2289. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2290. const char *StartSpecifier,
  2291. unsigned SpecifierLen,
  2292. const Expr *E) {
  2293. using namespace analyze_format_string;
  2294. using namespace analyze_printf;
  2295. // Now type check the data expression that matches the
  2296. // format specifier.
  2297. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  2298. ObjCContext);
  2299. if (AT.isValid() && !AT.matchesType(S.Context, E->getType())) {
  2300. // Look through argument promotions for our error message's reported type.
  2301. // This includes the integral and floating promotions, but excludes array
  2302. // and function pointer decay; seeing that an argument intended to be a
  2303. // string has type 'char [6]' is probably more confusing than 'char *'.
  2304. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2305. if (ICE->getCastKind() == CK_IntegralCast ||
  2306. ICE->getCastKind() == CK_FloatingCast) {
  2307. E = ICE->getSubExpr();
  2308. // Check if we didn't match because of an implicit cast from a 'char'
  2309. // or 'short' to an 'int'. This is done because printf is a varargs
  2310. // function.
  2311. if (ICE->getType() == S.Context.IntTy ||
  2312. ICE->getType() == S.Context.UnsignedIntTy) {
  2313. // All further checking is done on the subexpression.
  2314. if (AT.matchesType(S.Context, E->getType()))
  2315. return true;
  2316. }
  2317. }
  2318. }
  2319. // We may be able to offer a FixItHint if it is a supported type.
  2320. PrintfSpecifier fixedFS = FS;
  2321. bool success = fixedFS.fixType(E->getType(), S.getLangOpts(),
  2322. S.Context, ObjCContext);
  2323. if (success) {
  2324. // Get the fix string from the fixed format specifier
  2325. SmallString<16> buf;
  2326. llvm::raw_svector_ostream os(buf);
  2327. fixedFS.toString(os);
  2328. EmitFormatDiagnostic(
  2329. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2330. << AT.getRepresentativeTypeName(S.Context) << E->getType()
  2331. << E->getSourceRange(),
  2332. E->getLocStart(),
  2333. /*IsStringLocation*/false,
  2334. getSpecifierRange(StartSpecifier, SpecifierLen),
  2335. FixItHint::CreateReplacement(
  2336. getSpecifierRange(StartSpecifier, SpecifierLen),
  2337. os.str()));
  2338. } else {
  2339. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  2340. SpecifierLen);
  2341. // Since the warning for passing non-POD types to variadic functions
  2342. // was deferred until now, we emit a warning for non-POD
  2343. // arguments here.
  2344. if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
  2345. unsigned DiagKind;
  2346. if (E->getType()->isObjCObjectType())
  2347. DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
  2348. else
  2349. DiagKind = diag::warn_non_pod_vararg_with_format_string;
  2350. EmitFormatDiagnostic(
  2351. S.PDiag(DiagKind)
  2352. << S.getLangOpts().CPlusPlus0x
  2353. << E->getType()
  2354. << CallType
  2355. << AT.getRepresentativeTypeName(S.Context)
  2356. << CSR
  2357. << E->getSourceRange(),
  2358. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2359. checkForCStrMembers(AT, E, CSR);
  2360. } else
  2361. EmitFormatDiagnostic(
  2362. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2363. << AT.getRepresentativeTypeName(S.Context) << E->getType()
  2364. << CSR
  2365. << E->getSourceRange(),
  2366. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2367. }
  2368. }
  2369. return true;
  2370. }
  2371. //===--- CHECK: Scanf format string checking ------------------------------===//
  2372. namespace {
  2373. class CheckScanfHandler : public CheckFormatHandler {
  2374. public:
  2375. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  2376. const Expr *origFormatExpr, unsigned firstDataArg,
  2377. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2378. Expr **Args, unsigned NumArgs,
  2379. unsigned formatIdx, bool inFunctionCall,
  2380. Sema::VariadicCallType CallType)
  2381. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2382. numDataArgs, beg, hasVAListArg,
  2383. Args, NumArgs, formatIdx, inFunctionCall, CallType)
  2384. {}
  2385. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  2386. const char *startSpecifier,
  2387. unsigned specifierLen);
  2388. bool HandleInvalidScanfConversionSpecifier(
  2389. const analyze_scanf::ScanfSpecifier &FS,
  2390. const char *startSpecifier,
  2391. unsigned specifierLen);
  2392. void HandleIncompleteScanList(const char *start, const char *end);
  2393. };
  2394. }
  2395. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  2396. const char *end) {
  2397. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  2398. getLocationOfByte(end), /*IsStringLocation*/true,
  2399. getSpecifierRange(start, end - start));
  2400. }
  2401. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  2402. const analyze_scanf::ScanfSpecifier &FS,
  2403. const char *startSpecifier,
  2404. unsigned specifierLen) {
  2405. const analyze_scanf::ScanfConversionSpecifier &CS =
  2406. FS.getConversionSpecifier();
  2407. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2408. getLocationOfByte(CS.getStart()),
  2409. startSpecifier, specifierLen,
  2410. CS.getStart(), CS.getLength());
  2411. }
  2412. bool CheckScanfHandler::HandleScanfSpecifier(
  2413. const analyze_scanf::ScanfSpecifier &FS,
  2414. const char *startSpecifier,
  2415. unsigned specifierLen) {
  2416. using namespace analyze_scanf;
  2417. using namespace analyze_format_string;
  2418. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  2419. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  2420. // be used to decide if we are using positional arguments consistently.
  2421. if (FS.consumesDataArgument()) {
  2422. if (atFirstArg) {
  2423. atFirstArg = false;
  2424. usesPositionalArgs = FS.usesPositionalArg();
  2425. }
  2426. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2427. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2428. startSpecifier, specifierLen);
  2429. return false;
  2430. }
  2431. }
  2432. // Check if the field with is non-zero.
  2433. const OptionalAmount &Amt = FS.getFieldWidth();
  2434. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  2435. if (Amt.getConstantAmount() == 0) {
  2436. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  2437. Amt.getConstantLength());
  2438. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  2439. getLocationOfByte(Amt.getStart()),
  2440. /*IsStringLocation*/true, R,
  2441. FixItHint::CreateRemoval(R));
  2442. }
  2443. }
  2444. if (!FS.consumesDataArgument()) {
  2445. // FIXME: Technically specifying a precision or field width here
  2446. // makes no sense. Worth issuing a warning at some point.
  2447. return true;
  2448. }
  2449. // Consume the argument.
  2450. unsigned argIndex = FS.getArgIndex();
  2451. if (argIndex < NumDataArgs) {
  2452. // The check to see if the argIndex is valid will come later.
  2453. // We set the bit here because we may exit early from this
  2454. // function if we encounter some other error.
  2455. CoveredArgs.set(argIndex);
  2456. }
  2457. // Check the length modifier is valid with the given conversion specifier.
  2458. const LengthModifier &LM = FS.getLengthModifier();
  2459. if (!FS.hasValidLengthModifier()) {
  2460. const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
  2461. EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
  2462. << LM.toString() << CS.toString()
  2463. << getSpecifierRange(startSpecifier, specifierLen),
  2464. getLocationOfByte(LM.getStart()),
  2465. /*IsStringLocation*/true, R,
  2466. FixItHint::CreateRemoval(R));
  2467. }
  2468. if (!FS.hasStandardLengthModifier())
  2469. HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
  2470. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2471. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2472. if (!FS.hasStandardLengthConversionCombination())
  2473. HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
  2474. specifierLen);
  2475. // The remaining checks depend on the data arguments.
  2476. if (HasVAListArg)
  2477. return true;
  2478. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2479. return false;
  2480. // Check that the argument type matches the format specifier.
  2481. const Expr *Ex = getDataArg(argIndex);
  2482. if (!Ex)
  2483. return true;
  2484. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  2485. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
  2486. ScanfSpecifier fixedFS = FS;
  2487. bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
  2488. S.Context);
  2489. if (success) {
  2490. // Get the fix string from the fixed format specifier.
  2491. SmallString<128> buf;
  2492. llvm::raw_svector_ostream os(buf);
  2493. fixedFS.toString(os);
  2494. EmitFormatDiagnostic(
  2495. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2496. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2497. << Ex->getSourceRange(),
  2498. Ex->getLocStart(),
  2499. /*IsStringLocation*/false,
  2500. getSpecifierRange(startSpecifier, specifierLen),
  2501. FixItHint::CreateReplacement(
  2502. getSpecifierRange(startSpecifier, specifierLen),
  2503. os.str()));
  2504. } else {
  2505. EmitFormatDiagnostic(
  2506. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2507. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2508. << Ex->getSourceRange(),
  2509. Ex->getLocStart(),
  2510. /*IsStringLocation*/false,
  2511. getSpecifierRange(startSpecifier, specifierLen));
  2512. }
  2513. }
  2514. return true;
  2515. }
  2516. void Sema::CheckFormatString(const StringLiteral *FExpr,
  2517. const Expr *OrigFormatExpr,
  2518. Expr **Args, unsigned NumArgs,
  2519. bool HasVAListArg, unsigned format_idx,
  2520. unsigned firstDataArg, FormatStringType Type,
  2521. bool inFunctionCall, VariadicCallType CallType) {
  2522. // CHECK: is the format string a wide literal?
  2523. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  2524. CheckFormatHandler::EmitFormatDiagnostic(
  2525. *this, inFunctionCall, Args[format_idx],
  2526. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  2527. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2528. return;
  2529. }
  2530. // Str - The format string. NOTE: this is NOT null-terminated!
  2531. StringRef StrRef = FExpr->getString();
  2532. const char *Str = StrRef.data();
  2533. unsigned StrLen = StrRef.size();
  2534. const unsigned numDataArgs = NumArgs - firstDataArg;
  2535. // CHECK: empty format string?
  2536. if (StrLen == 0 && numDataArgs > 0) {
  2537. CheckFormatHandler::EmitFormatDiagnostic(
  2538. *this, inFunctionCall, Args[format_idx],
  2539. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  2540. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2541. return;
  2542. }
  2543. if (Type == FST_Printf || Type == FST_NSString) {
  2544. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  2545. numDataArgs, (Type == FST_NSString),
  2546. Str, HasVAListArg, Args, NumArgs, format_idx,
  2547. inFunctionCall, CallType);
  2548. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  2549. getLangOpts()))
  2550. H.DoneProcessing();
  2551. } else if (Type == FST_Scanf) {
  2552. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  2553. Str, HasVAListArg, Args, NumArgs, format_idx,
  2554. inFunctionCall, CallType);
  2555. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  2556. getLangOpts()))
  2557. H.DoneProcessing();
  2558. } // TODO: handle other formats
  2559. }
  2560. //===--- CHECK: Standard memory functions ---------------------------------===//
  2561. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  2562. /// whether it has a vtable).
  2563. static bool isDynamicClassType(QualType T) {
  2564. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  2565. if (CXXRecordDecl *Definition = Record->getDefinition())
  2566. if (Definition->isDynamicClass())
  2567. return true;
  2568. return false;
  2569. }
  2570. /// \brief If E is a sizeof expression, returns its argument expression,
  2571. /// otherwise returns NULL.
  2572. static const Expr *getSizeOfExprArg(const Expr* E) {
  2573. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2574. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2575. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  2576. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  2577. return 0;
  2578. }
  2579. /// \brief If E is a sizeof expression, returns its argument type.
  2580. static QualType getSizeOfArgType(const Expr* E) {
  2581. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2582. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2583. if (SizeOf->getKind() == clang::UETT_SizeOf)
  2584. return SizeOf->getTypeOfArgument();
  2585. return QualType();
  2586. }
  2587. /// \brief Check for dangerous or invalid arguments to memset().
  2588. ///
  2589. /// This issues warnings on known problematic, dangerous or unspecified
  2590. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  2591. /// function calls.
  2592. ///
  2593. /// \param Call The call expression to diagnose.
  2594. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  2595. unsigned BId,
  2596. IdentifierInfo *FnName) {
  2597. assert(BId != 0);
  2598. // It is possible to have a non-standard definition of memset. Validate
  2599. // we have enough arguments, and if not, abort further checking.
  2600. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  2601. if (Call->getNumArgs() < ExpectedNumArgs)
  2602. return;
  2603. unsigned LastArg = (BId == Builtin::BImemset ||
  2604. BId == Builtin::BIstrndup ? 1 : 2);
  2605. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  2606. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  2607. // We have special checking when the length is a sizeof expression.
  2608. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  2609. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  2610. llvm::FoldingSetNodeID SizeOfArgID;
  2611. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  2612. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  2613. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  2614. QualType DestTy = Dest->getType();
  2615. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  2616. QualType PointeeTy = DestPtrTy->getPointeeType();
  2617. // Never warn about void type pointers. This can be used to suppress
  2618. // false positives.
  2619. if (PointeeTy->isVoidType())
  2620. continue;
  2621. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  2622. // actually comparing the expressions for equality. Because computing the
  2623. // expression IDs can be expensive, we only do this if the diagnostic is
  2624. // enabled.
  2625. if (SizeOfArg &&
  2626. Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
  2627. SizeOfArg->getExprLoc())) {
  2628. // We only compute IDs for expressions if the warning is enabled, and
  2629. // cache the sizeof arg's ID.
  2630. if (SizeOfArgID == llvm::FoldingSetNodeID())
  2631. SizeOfArg->Profile(SizeOfArgID, Context, true);
  2632. llvm::FoldingSetNodeID DestID;
  2633. Dest->Profile(DestID, Context, true);
  2634. if (DestID == SizeOfArgID) {
  2635. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  2636. // over sizeof(src) as well.
  2637. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  2638. StringRef ReadableName = FnName->getName();
  2639. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  2640. if (UnaryOp->getOpcode() == UO_AddrOf)
  2641. ActionIdx = 1; // If its an address-of operator, just remove it.
  2642. if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
  2643. ActionIdx = 2; // If the pointee's size is sizeof(char),
  2644. // suggest an explicit length.
  2645. // If the function is defined as a builtin macro, do not show macro
  2646. // expansion.
  2647. SourceLocation SL = SizeOfArg->getExprLoc();
  2648. SourceRange DSR = Dest->getSourceRange();
  2649. SourceRange SSR = SizeOfArg->getSourceRange();
  2650. SourceManager &SM = PP.getSourceManager();
  2651. if (SM.isMacroArgExpansion(SL)) {
  2652. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  2653. SL = SM.getSpellingLoc(SL);
  2654. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  2655. SM.getSpellingLoc(DSR.getEnd()));
  2656. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  2657. SM.getSpellingLoc(SSR.getEnd()));
  2658. }
  2659. DiagRuntimeBehavior(SL, SizeOfArg,
  2660. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  2661. << ReadableName
  2662. << PointeeTy
  2663. << DestTy
  2664. << DSR
  2665. << SSR);
  2666. DiagRuntimeBehavior(SL, SizeOfArg,
  2667. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  2668. << ActionIdx
  2669. << SSR);
  2670. break;
  2671. }
  2672. }
  2673. // Also check for cases where the sizeof argument is the exact same
  2674. // type as the memory argument, and where it points to a user-defined
  2675. // record type.
  2676. if (SizeOfArgTy != QualType()) {
  2677. if (PointeeTy->isRecordType() &&
  2678. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  2679. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  2680. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  2681. << FnName << SizeOfArgTy << ArgIdx
  2682. << PointeeTy << Dest->getSourceRange()
  2683. << LenExpr->getSourceRange());
  2684. break;
  2685. }
  2686. }
  2687. // Always complain about dynamic classes.
  2688. if (isDynamicClassType(PointeeTy)) {
  2689. unsigned OperationType = 0;
  2690. // "overwritten" if we're warning about the destination for any call
  2691. // but memcmp; otherwise a verb appropriate to the call.
  2692. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  2693. if (BId == Builtin::BImemcpy)
  2694. OperationType = 1;
  2695. else if(BId == Builtin::BImemmove)
  2696. OperationType = 2;
  2697. else if (BId == Builtin::BImemcmp)
  2698. OperationType = 3;
  2699. }
  2700. DiagRuntimeBehavior(
  2701. Dest->getExprLoc(), Dest,
  2702. PDiag(diag::warn_dyn_class_memaccess)
  2703. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  2704. << FnName << PointeeTy
  2705. << OperationType
  2706. << Call->getCallee()->getSourceRange());
  2707. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  2708. BId != Builtin::BImemset)
  2709. DiagRuntimeBehavior(
  2710. Dest->getExprLoc(), Dest,
  2711. PDiag(diag::warn_arc_object_memaccess)
  2712. << ArgIdx << FnName << PointeeTy
  2713. << Call->getCallee()->getSourceRange());
  2714. else
  2715. continue;
  2716. DiagRuntimeBehavior(
  2717. Dest->getExprLoc(), Dest,
  2718. PDiag(diag::note_bad_memaccess_silence)
  2719. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  2720. break;
  2721. }
  2722. }
  2723. }
  2724. // A little helper routine: ignore addition and subtraction of integer literals.
  2725. // This intentionally does not ignore all integer constant expressions because
  2726. // we don't want to remove sizeof().
  2727. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  2728. Ex = Ex->IgnoreParenCasts();
  2729. for (;;) {
  2730. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  2731. if (!BO || !BO->isAdditiveOp())
  2732. break;
  2733. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  2734. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  2735. if (isa<IntegerLiteral>(RHS))
  2736. Ex = LHS;
  2737. else if (isa<IntegerLiteral>(LHS))
  2738. Ex = RHS;
  2739. else
  2740. break;
  2741. }
  2742. return Ex;
  2743. }
  2744. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  2745. ASTContext &Context) {
  2746. // Only handle constant-sized or VLAs, but not flexible members.
  2747. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  2748. // Only issue the FIXIT for arrays of size > 1.
  2749. if (CAT->getSize().getSExtValue() <= 1)
  2750. return false;
  2751. } else if (!Ty->isVariableArrayType()) {
  2752. return false;
  2753. }
  2754. return true;
  2755. }
  2756. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  2757. // be the size of the source, instead of the destination.
  2758. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  2759. IdentifierInfo *FnName) {
  2760. // Don't crash if the user has the wrong number of arguments
  2761. if (Call->getNumArgs() != 3)
  2762. return;
  2763. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  2764. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  2765. const Expr *CompareWithSrc = NULL;
  2766. // Look for 'strlcpy(dst, x, sizeof(x))'
  2767. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  2768. CompareWithSrc = Ex;
  2769. else {
  2770. // Look for 'strlcpy(dst, x, strlen(x))'
  2771. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  2772. if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
  2773. && SizeCall->getNumArgs() == 1)
  2774. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  2775. }
  2776. }
  2777. if (!CompareWithSrc)
  2778. return;
  2779. // Determine if the argument to sizeof/strlen is equal to the source
  2780. // argument. In principle there's all kinds of things you could do
  2781. // here, for instance creating an == expression and evaluating it with
  2782. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  2783. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  2784. if (!SrcArgDRE)
  2785. return;
  2786. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  2787. if (!CompareWithSrcDRE ||
  2788. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  2789. return;
  2790. const Expr *OriginalSizeArg = Call->getArg(2);
  2791. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  2792. << OriginalSizeArg->getSourceRange() << FnName;
  2793. // Output a FIXIT hint if the destination is an array (rather than a
  2794. // pointer to an array). This could be enhanced to handle some
  2795. // pointers if we know the actual size, like if DstArg is 'array+2'
  2796. // we could say 'sizeof(array)-2'.
  2797. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  2798. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  2799. return;
  2800. SmallString<128> sizeString;
  2801. llvm::raw_svector_ostream OS(sizeString);
  2802. OS << "sizeof(";
  2803. DstArg->printPretty(OS, 0, getPrintingPolicy());
  2804. OS << ")";
  2805. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  2806. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  2807. OS.str());
  2808. }
  2809. /// Check if two expressions refer to the same declaration.
  2810. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  2811. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  2812. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  2813. return D1->getDecl() == D2->getDecl();
  2814. return false;
  2815. }
  2816. static const Expr *getStrlenExprArg(const Expr *E) {
  2817. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  2818. const FunctionDecl *FD = CE->getDirectCallee();
  2819. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  2820. return 0;
  2821. return CE->getArg(0)->IgnoreParenCasts();
  2822. }
  2823. return 0;
  2824. }
  2825. // Warn on anti-patterns as the 'size' argument to strncat.
  2826. // The correct size argument should look like following:
  2827. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  2828. void Sema::CheckStrncatArguments(const CallExpr *CE,
  2829. IdentifierInfo *FnName) {
  2830. // Don't crash if the user has the wrong number of arguments.
  2831. if (CE->getNumArgs() < 3)
  2832. return;
  2833. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  2834. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  2835. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  2836. // Identify common expressions, which are wrongly used as the size argument
  2837. // to strncat and may lead to buffer overflows.
  2838. unsigned PatternType = 0;
  2839. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  2840. // - sizeof(dst)
  2841. if (referToTheSameDecl(SizeOfArg, DstArg))
  2842. PatternType = 1;
  2843. // - sizeof(src)
  2844. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  2845. PatternType = 2;
  2846. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  2847. if (BE->getOpcode() == BO_Sub) {
  2848. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  2849. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  2850. // - sizeof(dst) - strlen(dst)
  2851. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  2852. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  2853. PatternType = 1;
  2854. // - sizeof(src) - (anything)
  2855. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  2856. PatternType = 2;
  2857. }
  2858. }
  2859. if (PatternType == 0)
  2860. return;
  2861. // Generate the diagnostic.
  2862. SourceLocation SL = LenArg->getLocStart();
  2863. SourceRange SR = LenArg->getSourceRange();
  2864. SourceManager &SM = PP.getSourceManager();
  2865. // If the function is defined as a builtin macro, do not show macro expansion.
  2866. if (SM.isMacroArgExpansion(SL)) {
  2867. SL = SM.getSpellingLoc(SL);
  2868. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  2869. SM.getSpellingLoc(SR.getEnd()));
  2870. }
  2871. // Check if the destination is an array (rather than a pointer to an array).
  2872. QualType DstTy = DstArg->getType();
  2873. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  2874. Context);
  2875. if (!isKnownSizeArray) {
  2876. if (PatternType == 1)
  2877. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  2878. else
  2879. Diag(SL, diag::warn_strncat_src_size) << SR;
  2880. return;
  2881. }
  2882. if (PatternType == 1)
  2883. Diag(SL, diag::warn_strncat_large_size) << SR;
  2884. else
  2885. Diag(SL, diag::warn_strncat_src_size) << SR;
  2886. SmallString<128> sizeString;
  2887. llvm::raw_svector_ostream OS(sizeString);
  2888. OS << "sizeof(";
  2889. DstArg->printPretty(OS, 0, getPrintingPolicy());
  2890. OS << ") - ";
  2891. OS << "strlen(";
  2892. DstArg->printPretty(OS, 0, getPrintingPolicy());
  2893. OS << ") - 1";
  2894. Diag(SL, diag::note_strncat_wrong_size)
  2895. << FixItHint::CreateReplacement(SR, OS.str());
  2896. }
  2897. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  2898. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  2899. Decl *ParentDecl);
  2900. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  2901. Decl *ParentDecl);
  2902. /// CheckReturnStackAddr - Check if a return statement returns the address
  2903. /// of a stack variable.
  2904. void
  2905. Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
  2906. SourceLocation ReturnLoc) {
  2907. Expr *stackE = 0;
  2908. SmallVector<DeclRefExpr *, 8> refVars;
  2909. // Perform checking for returned stack addresses, local blocks,
  2910. // label addresses or references to temporaries.
  2911. if (lhsType->isPointerType() ||
  2912. (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  2913. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
  2914. } else if (lhsType->isReferenceType()) {
  2915. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
  2916. }
  2917. if (stackE == 0)
  2918. return; // Nothing suspicious was found.
  2919. SourceLocation diagLoc;
  2920. SourceRange diagRange;
  2921. if (refVars.empty()) {
  2922. diagLoc = stackE->getLocStart();
  2923. diagRange = stackE->getSourceRange();
  2924. } else {
  2925. // We followed through a reference variable. 'stackE' contains the
  2926. // problematic expression but we will warn at the return statement pointing
  2927. // at the reference variable. We will later display the "trail" of
  2928. // reference variables using notes.
  2929. diagLoc = refVars[0]->getLocStart();
  2930. diagRange = refVars[0]->getSourceRange();
  2931. }
  2932. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  2933. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  2934. : diag::warn_ret_stack_addr)
  2935. << DR->getDecl()->getDeclName() << diagRange;
  2936. } else if (isa<BlockExpr>(stackE)) { // local block.
  2937. Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  2938. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  2939. Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  2940. } else { // local temporary.
  2941. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  2942. : diag::warn_ret_local_temp_addr)
  2943. << diagRange;
  2944. }
  2945. // Display the "trail" of reference variables that we followed until we
  2946. // found the problematic expression using notes.
  2947. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  2948. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  2949. // If this var binds to another reference var, show the range of the next
  2950. // var, otherwise the var binds to the problematic expression, in which case
  2951. // show the range of the expression.
  2952. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  2953. : stackE->getSourceRange();
  2954. Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  2955. << VD->getDeclName() << range;
  2956. }
  2957. }
  2958. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  2959. /// check if the expression in a return statement evaluates to an address
  2960. /// to a location on the stack, a local block, an address of a label, or a
  2961. /// reference to local temporary. The recursion is used to traverse the
  2962. /// AST of the return expression, with recursion backtracking when we
  2963. /// encounter a subexpression that (1) clearly does not lead to one of the
  2964. /// above problematic expressions (2) is something we cannot determine leads to
  2965. /// a problematic expression based on such local checking.
  2966. ///
  2967. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  2968. /// the expression that they point to. Such variables are added to the
  2969. /// 'refVars' vector so that we know what the reference variable "trail" was.
  2970. ///
  2971. /// EvalAddr processes expressions that are pointers that are used as
  2972. /// references (and not L-values). EvalVal handles all other values.
  2973. /// At the base case of the recursion is a check for the above problematic
  2974. /// expressions.
  2975. ///
  2976. /// This implementation handles:
  2977. ///
  2978. /// * pointer-to-pointer casts
  2979. /// * implicit conversions from array references to pointers
  2980. /// * taking the address of fields
  2981. /// * arbitrary interplay between "&" and "*" operators
  2982. /// * pointer arithmetic from an address of a stack variable
  2983. /// * taking the address of an array element where the array is on the stack
  2984. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  2985. Decl *ParentDecl) {
  2986. if (E->isTypeDependent())
  2987. return NULL;
  2988. // We should only be called for evaluating pointer expressions.
  2989. assert((E->getType()->isAnyPointerType() ||
  2990. E->getType()->isBlockPointerType() ||
  2991. E->getType()->isObjCQualifiedIdType()) &&
  2992. "EvalAddr only works on pointers");
  2993. E = E->IgnoreParens();
  2994. // Our "symbolic interpreter" is just a dispatch off the currently
  2995. // viewed AST node. We then recursively traverse the AST by calling
  2996. // EvalAddr and EvalVal appropriately.
  2997. switch (E->getStmtClass()) {
  2998. case Stmt::DeclRefExprClass: {
  2999. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3000. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  3001. // If this is a reference variable, follow through to the expression that
  3002. // it points to.
  3003. if (V->hasLocalStorage() &&
  3004. V->getType()->isReferenceType() && V->hasInit()) {
  3005. // Add the reference variable to the "trail".
  3006. refVars.push_back(DR);
  3007. return EvalAddr(V->getInit(), refVars, ParentDecl);
  3008. }
  3009. return NULL;
  3010. }
  3011. case Stmt::UnaryOperatorClass: {
  3012. // The only unary operator that make sense to handle here
  3013. // is AddrOf. All others don't make sense as pointers.
  3014. UnaryOperator *U = cast<UnaryOperator>(E);
  3015. if (U->getOpcode() == UO_AddrOf)
  3016. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  3017. else
  3018. return NULL;
  3019. }
  3020. case Stmt::BinaryOperatorClass: {
  3021. // Handle pointer arithmetic. All other binary operators are not valid
  3022. // in this context.
  3023. BinaryOperator *B = cast<BinaryOperator>(E);
  3024. BinaryOperatorKind op = B->getOpcode();
  3025. if (op != BO_Add && op != BO_Sub)
  3026. return NULL;
  3027. Expr *Base = B->getLHS();
  3028. // Determine which argument is the real pointer base. It could be
  3029. // the RHS argument instead of the LHS.
  3030. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  3031. assert (Base->getType()->isPointerType());
  3032. return EvalAddr(Base, refVars, ParentDecl);
  3033. }
  3034. // For conditional operators we need to see if either the LHS or RHS are
  3035. // valid DeclRefExpr*s. If one of them is valid, we return it.
  3036. case Stmt::ConditionalOperatorClass: {
  3037. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3038. // Handle the GNU extension for missing LHS.
  3039. if (Expr *lhsExpr = C->getLHS()) {
  3040. // In C++, we can have a throw-expression, which has 'void' type.
  3041. if (!lhsExpr->getType()->isVoidType())
  3042. if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
  3043. return LHS;
  3044. }
  3045. // In C++, we can have a throw-expression, which has 'void' type.
  3046. if (C->getRHS()->getType()->isVoidType())
  3047. return NULL;
  3048. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  3049. }
  3050. case Stmt::BlockExprClass:
  3051. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  3052. return E; // local block.
  3053. return NULL;
  3054. case Stmt::AddrLabelExprClass:
  3055. return E; // address of label.
  3056. case Stmt::ExprWithCleanupsClass:
  3057. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  3058. ParentDecl);
  3059. // For casts, we need to handle conversions from arrays to
  3060. // pointer values, and pointer-to-pointer conversions.
  3061. case Stmt::ImplicitCastExprClass:
  3062. case Stmt::CStyleCastExprClass:
  3063. case Stmt::CXXFunctionalCastExprClass:
  3064. case Stmt::ObjCBridgedCastExprClass:
  3065. case Stmt::CXXStaticCastExprClass:
  3066. case Stmt::CXXDynamicCastExprClass:
  3067. case Stmt::CXXConstCastExprClass:
  3068. case Stmt::CXXReinterpretCastExprClass: {
  3069. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  3070. switch (cast<CastExpr>(E)->getCastKind()) {
  3071. case CK_BitCast:
  3072. case CK_LValueToRValue:
  3073. case CK_NoOp:
  3074. case CK_BaseToDerived:
  3075. case CK_DerivedToBase:
  3076. case CK_UncheckedDerivedToBase:
  3077. case CK_Dynamic:
  3078. case CK_CPointerToObjCPointerCast:
  3079. case CK_BlockPointerToObjCPointerCast:
  3080. case CK_AnyPointerToBlockPointerCast:
  3081. return EvalAddr(SubExpr, refVars, ParentDecl);
  3082. case CK_ArrayToPointerDecay:
  3083. return EvalVal(SubExpr, refVars, ParentDecl);
  3084. default:
  3085. return 0;
  3086. }
  3087. }
  3088. case Stmt::MaterializeTemporaryExprClass:
  3089. if (Expr *Result = EvalAddr(
  3090. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3091. refVars, ParentDecl))
  3092. return Result;
  3093. return E;
  3094. // Everything else: we simply don't reason about them.
  3095. default:
  3096. return NULL;
  3097. }
  3098. }
  3099. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  3100. /// See the comments for EvalAddr for more details.
  3101. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3102. Decl *ParentDecl) {
  3103. do {
  3104. // We should only be called for evaluating non-pointer expressions, or
  3105. // expressions with a pointer type that are not used as references but instead
  3106. // are l-values (e.g., DeclRefExpr with a pointer type).
  3107. // Our "symbolic interpreter" is just a dispatch off the currently
  3108. // viewed AST node. We then recursively traverse the AST by calling
  3109. // EvalAddr and EvalVal appropriately.
  3110. E = E->IgnoreParens();
  3111. switch (E->getStmtClass()) {
  3112. case Stmt::ImplicitCastExprClass: {
  3113. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  3114. if (IE->getValueKind() == VK_LValue) {
  3115. E = IE->getSubExpr();
  3116. continue;
  3117. }
  3118. return NULL;
  3119. }
  3120. case Stmt::ExprWithCleanupsClass:
  3121. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  3122. case Stmt::DeclRefExprClass: {
  3123. // When we hit a DeclRefExpr we are looking at code that refers to a
  3124. // variable's name. If it's not a reference variable we check if it has
  3125. // local storage within the function, and if so, return the expression.
  3126. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3127. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  3128. // Check if it refers to itself, e.g. "int& i = i;".
  3129. if (V == ParentDecl)
  3130. return DR;
  3131. if (V->hasLocalStorage()) {
  3132. if (!V->getType()->isReferenceType())
  3133. return DR;
  3134. // Reference variable, follow through to the expression that
  3135. // it points to.
  3136. if (V->hasInit()) {
  3137. // Add the reference variable to the "trail".
  3138. refVars.push_back(DR);
  3139. return EvalVal(V->getInit(), refVars, V);
  3140. }
  3141. }
  3142. }
  3143. return NULL;
  3144. }
  3145. case Stmt::UnaryOperatorClass: {
  3146. // The only unary operator that make sense to handle here
  3147. // is Deref. All others don't resolve to a "name." This includes
  3148. // handling all sorts of rvalues passed to a unary operator.
  3149. UnaryOperator *U = cast<UnaryOperator>(E);
  3150. if (U->getOpcode() == UO_Deref)
  3151. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  3152. return NULL;
  3153. }
  3154. case Stmt::ArraySubscriptExprClass: {
  3155. // Array subscripts are potential references to data on the stack. We
  3156. // retrieve the DeclRefExpr* for the array variable if it indeed
  3157. // has local storage.
  3158. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  3159. }
  3160. case Stmt::ConditionalOperatorClass: {
  3161. // For conditional operators we need to see if either the LHS or RHS are
  3162. // non-NULL Expr's. If one is non-NULL, we return it.
  3163. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3164. // Handle the GNU extension for missing LHS.
  3165. if (Expr *lhsExpr = C->getLHS())
  3166. if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
  3167. return LHS;
  3168. return EvalVal(C->getRHS(), refVars, ParentDecl);
  3169. }
  3170. // Accesses to members are potential references to data on the stack.
  3171. case Stmt::MemberExprClass: {
  3172. MemberExpr *M = cast<MemberExpr>(E);
  3173. // Check for indirect access. We only want direct field accesses.
  3174. if (M->isArrow())
  3175. return NULL;
  3176. // Check whether the member type is itself a reference, in which case
  3177. // we're not going to refer to the member, but to what the member refers to.
  3178. if (M->getMemberDecl()->getType()->isReferenceType())
  3179. return NULL;
  3180. return EvalVal(M->getBase(), refVars, ParentDecl);
  3181. }
  3182. case Stmt::MaterializeTemporaryExprClass:
  3183. if (Expr *Result = EvalVal(
  3184. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3185. refVars, ParentDecl))
  3186. return Result;
  3187. return E;
  3188. default:
  3189. // Check that we don't return or take the address of a reference to a
  3190. // temporary. This is only useful in C++.
  3191. if (!E->isTypeDependent() && E->isRValue())
  3192. return E;
  3193. // Everything else: we simply don't reason about them.
  3194. return NULL;
  3195. }
  3196. } while (true);
  3197. }
  3198. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  3199. /// Check for comparisons of floating point operands using != and ==.
  3200. /// Issue a warning if these are no self-comparisons, as they are not likely
  3201. /// to do what the programmer intended.
  3202. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  3203. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  3204. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  3205. // Special case: check for x == x (which is OK).
  3206. // Do not emit warnings for such cases.
  3207. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  3208. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  3209. if (DRL->getDecl() == DRR->getDecl())
  3210. return;
  3211. // Special case: check for comparisons against literals that can be exactly
  3212. // represented by APFloat. In such cases, do not emit a warning. This
  3213. // is a heuristic: often comparison against such literals are used to
  3214. // detect if a value in a variable has not changed. This clearly can
  3215. // lead to false negatives.
  3216. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  3217. if (FLL->isExact())
  3218. return;
  3219. } else
  3220. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  3221. if (FLR->isExact())
  3222. return;
  3223. // Check for comparisons with builtin types.
  3224. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  3225. if (CL->isBuiltinCall())
  3226. return;
  3227. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  3228. if (CR->isBuiltinCall())
  3229. return;
  3230. // Emit the diagnostic.
  3231. Diag(Loc, diag::warn_floatingpoint_eq)
  3232. << LHS->getSourceRange() << RHS->getSourceRange();
  3233. }
  3234. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  3235. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  3236. namespace {
  3237. /// Structure recording the 'active' range of an integer-valued
  3238. /// expression.
  3239. struct IntRange {
  3240. /// The number of bits active in the int.
  3241. unsigned Width;
  3242. /// True if the int is known not to have negative values.
  3243. bool NonNegative;
  3244. IntRange(unsigned Width, bool NonNegative)
  3245. : Width(Width), NonNegative(NonNegative)
  3246. {}
  3247. /// Returns the range of the bool type.
  3248. static IntRange forBoolType() {
  3249. return IntRange(1, true);
  3250. }
  3251. /// Returns the range of an opaque value of the given integral type.
  3252. static IntRange forValueOfType(ASTContext &C, QualType T) {
  3253. return forValueOfCanonicalType(C,
  3254. T->getCanonicalTypeInternal().getTypePtr());
  3255. }
  3256. /// Returns the range of an opaque value of a canonical integral type.
  3257. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  3258. assert(T->isCanonicalUnqualified());
  3259. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3260. T = VT->getElementType().getTypePtr();
  3261. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3262. T = CT->getElementType().getTypePtr();
  3263. // For enum types, use the known bit width of the enumerators.
  3264. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  3265. EnumDecl *Enum = ET->getDecl();
  3266. if (!Enum->isCompleteDefinition())
  3267. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  3268. unsigned NumPositive = Enum->getNumPositiveBits();
  3269. unsigned NumNegative = Enum->getNumNegativeBits();
  3270. return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
  3271. }
  3272. const BuiltinType *BT = cast<BuiltinType>(T);
  3273. assert(BT->isInteger());
  3274. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3275. }
  3276. /// Returns the "target" range of a canonical integral type, i.e.
  3277. /// the range of values expressible in the type.
  3278. ///
  3279. /// This matches forValueOfCanonicalType except that enums have the
  3280. /// full range of their type, not the range of their enumerators.
  3281. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  3282. assert(T->isCanonicalUnqualified());
  3283. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3284. T = VT->getElementType().getTypePtr();
  3285. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3286. T = CT->getElementType().getTypePtr();
  3287. if (const EnumType *ET = dyn_cast<EnumType>(T))
  3288. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  3289. const BuiltinType *BT = cast<BuiltinType>(T);
  3290. assert(BT->isInteger());
  3291. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3292. }
  3293. /// Returns the supremum of two ranges: i.e. their conservative merge.
  3294. static IntRange join(IntRange L, IntRange R) {
  3295. return IntRange(std::max(L.Width, R.Width),
  3296. L.NonNegative && R.NonNegative);
  3297. }
  3298. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  3299. static IntRange meet(IntRange L, IntRange R) {
  3300. return IntRange(std::min(L.Width, R.Width),
  3301. L.NonNegative || R.NonNegative);
  3302. }
  3303. };
  3304. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  3305. unsigned MaxWidth) {
  3306. if (value.isSigned() && value.isNegative())
  3307. return IntRange(value.getMinSignedBits(), false);
  3308. if (value.getBitWidth() > MaxWidth)
  3309. value = value.trunc(MaxWidth);
  3310. // isNonNegative() just checks the sign bit without considering
  3311. // signedness.
  3312. return IntRange(value.getActiveBits(), true);
  3313. }
  3314. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  3315. unsigned MaxWidth) {
  3316. if (result.isInt())
  3317. return GetValueRange(C, result.getInt(), MaxWidth);
  3318. if (result.isVector()) {
  3319. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  3320. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  3321. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  3322. R = IntRange::join(R, El);
  3323. }
  3324. return R;
  3325. }
  3326. if (result.isComplexInt()) {
  3327. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  3328. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  3329. return IntRange::join(R, I);
  3330. }
  3331. // This can happen with lossless casts to intptr_t of "based" lvalues.
  3332. // Assume it might use arbitrary bits.
  3333. // FIXME: The only reason we need to pass the type in here is to get
  3334. // the sign right on this one case. It would be nice if APValue
  3335. // preserved this.
  3336. assert(result.isLValue() || result.isAddrLabelDiff());
  3337. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  3338. }
  3339. /// Pseudo-evaluate the given integer expression, estimating the
  3340. /// range of values it might take.
  3341. ///
  3342. /// \param MaxWidth - the width to which the value will be truncated
  3343. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  3344. E = E->IgnoreParens();
  3345. // Try a full evaluation first.
  3346. Expr::EvalResult result;
  3347. if (E->EvaluateAsRValue(result, C))
  3348. return GetValueRange(C, result.Val, E->getType(), MaxWidth);
  3349. // I think we only want to look through implicit casts here; if the
  3350. // user has an explicit widening cast, we should treat the value as
  3351. // being of the new, wider type.
  3352. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  3353. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  3354. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  3355. IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
  3356. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  3357. // Assume that non-integer casts can span the full range of the type.
  3358. if (!isIntegerCast)
  3359. return OutputTypeRange;
  3360. IntRange SubRange
  3361. = GetExprRange(C, CE->getSubExpr(),
  3362. std::min(MaxWidth, OutputTypeRange.Width));
  3363. // Bail out if the subexpr's range is as wide as the cast type.
  3364. if (SubRange.Width >= OutputTypeRange.Width)
  3365. return OutputTypeRange;
  3366. // Otherwise, we take the smaller width, and we're non-negative if
  3367. // either the output type or the subexpr is.
  3368. return IntRange(SubRange.Width,
  3369. SubRange.NonNegative || OutputTypeRange.NonNegative);
  3370. }
  3371. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3372. // If we can fold the condition, just take that operand.
  3373. bool CondResult;
  3374. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  3375. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  3376. : CO->getFalseExpr(),
  3377. MaxWidth);
  3378. // Otherwise, conservatively merge.
  3379. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  3380. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  3381. return IntRange::join(L, R);
  3382. }
  3383. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3384. switch (BO->getOpcode()) {
  3385. // Boolean-valued operations are single-bit and positive.
  3386. case BO_LAnd:
  3387. case BO_LOr:
  3388. case BO_LT:
  3389. case BO_GT:
  3390. case BO_LE:
  3391. case BO_GE:
  3392. case BO_EQ:
  3393. case BO_NE:
  3394. return IntRange::forBoolType();
  3395. // The type of the assignments is the type of the LHS, so the RHS
  3396. // is not necessarily the same type.
  3397. case BO_MulAssign:
  3398. case BO_DivAssign:
  3399. case BO_RemAssign:
  3400. case BO_AddAssign:
  3401. case BO_SubAssign:
  3402. case BO_XorAssign:
  3403. case BO_OrAssign:
  3404. // TODO: bitfields?
  3405. return IntRange::forValueOfType(C, E->getType());
  3406. // Simple assignments just pass through the RHS, which will have
  3407. // been coerced to the LHS type.
  3408. case BO_Assign:
  3409. // TODO: bitfields?
  3410. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3411. // Operations with opaque sources are black-listed.
  3412. case BO_PtrMemD:
  3413. case BO_PtrMemI:
  3414. return IntRange::forValueOfType(C, E->getType());
  3415. // Bitwise-and uses the *infinum* of the two source ranges.
  3416. case BO_And:
  3417. case BO_AndAssign:
  3418. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  3419. GetExprRange(C, BO->getRHS(), MaxWidth));
  3420. // Left shift gets black-listed based on a judgement call.
  3421. case BO_Shl:
  3422. // ...except that we want to treat '1 << (blah)' as logically
  3423. // positive. It's an important idiom.
  3424. if (IntegerLiteral *I
  3425. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  3426. if (I->getValue() == 1) {
  3427. IntRange R = IntRange::forValueOfType(C, E->getType());
  3428. return IntRange(R.Width, /*NonNegative*/ true);
  3429. }
  3430. }
  3431. // fallthrough
  3432. case BO_ShlAssign:
  3433. return IntRange::forValueOfType(C, E->getType());
  3434. // Right shift by a constant can narrow its left argument.
  3435. case BO_Shr:
  3436. case BO_ShrAssign: {
  3437. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3438. // If the shift amount is a positive constant, drop the width by
  3439. // that much.
  3440. llvm::APSInt shift;
  3441. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  3442. shift.isNonNegative()) {
  3443. unsigned zext = shift.getZExtValue();
  3444. if (zext >= L.Width)
  3445. L.Width = (L.NonNegative ? 0 : 1);
  3446. else
  3447. L.Width -= zext;
  3448. }
  3449. return L;
  3450. }
  3451. // Comma acts as its right operand.
  3452. case BO_Comma:
  3453. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3454. // Black-list pointer subtractions.
  3455. case BO_Sub:
  3456. if (BO->getLHS()->getType()->isPointerType())
  3457. return IntRange::forValueOfType(C, E->getType());
  3458. break;
  3459. // The width of a division result is mostly determined by the size
  3460. // of the LHS.
  3461. case BO_Div: {
  3462. // Don't 'pre-truncate' the operands.
  3463. unsigned opWidth = C.getIntWidth(E->getType());
  3464. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3465. // If the divisor is constant, use that.
  3466. llvm::APSInt divisor;
  3467. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  3468. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  3469. if (log2 >= L.Width)
  3470. L.Width = (L.NonNegative ? 0 : 1);
  3471. else
  3472. L.Width = std::min(L.Width - log2, MaxWidth);
  3473. return L;
  3474. }
  3475. // Otherwise, just use the LHS's width.
  3476. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3477. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  3478. }
  3479. // The result of a remainder can't be larger than the result of
  3480. // either side.
  3481. case BO_Rem: {
  3482. // Don't 'pre-truncate' the operands.
  3483. unsigned opWidth = C.getIntWidth(E->getType());
  3484. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3485. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3486. IntRange meet = IntRange::meet(L, R);
  3487. meet.Width = std::min(meet.Width, MaxWidth);
  3488. return meet;
  3489. }
  3490. // The default behavior is okay for these.
  3491. case BO_Mul:
  3492. case BO_Add:
  3493. case BO_Xor:
  3494. case BO_Or:
  3495. break;
  3496. }
  3497. // The default case is to treat the operation as if it were closed
  3498. // on the narrowest type that encompasses both operands.
  3499. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3500. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  3501. return IntRange::join(L, R);
  3502. }
  3503. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  3504. switch (UO->getOpcode()) {
  3505. // Boolean-valued operations are white-listed.
  3506. case UO_LNot:
  3507. return IntRange::forBoolType();
  3508. // Operations with opaque sources are black-listed.
  3509. case UO_Deref:
  3510. case UO_AddrOf: // should be impossible
  3511. return IntRange::forValueOfType(C, E->getType());
  3512. default:
  3513. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  3514. }
  3515. }
  3516. if (dyn_cast<OffsetOfExpr>(E)) {
  3517. IntRange::forValueOfType(C, E->getType());
  3518. }
  3519. if (FieldDecl *BitField = E->getBitField())
  3520. return IntRange(BitField->getBitWidthValue(C),
  3521. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  3522. return IntRange::forValueOfType(C, E->getType());
  3523. }
  3524. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  3525. return GetExprRange(C, E, C.getIntWidth(E->getType()));
  3526. }
  3527. /// Checks whether the given value, which currently has the given
  3528. /// source semantics, has the same value when coerced through the
  3529. /// target semantics.
  3530. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  3531. const llvm::fltSemantics &Src,
  3532. const llvm::fltSemantics &Tgt) {
  3533. llvm::APFloat truncated = value;
  3534. bool ignored;
  3535. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3536. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3537. return truncated.bitwiseIsEqual(value);
  3538. }
  3539. /// Checks whether the given value, which currently has the given
  3540. /// source semantics, has the same value when coerced through the
  3541. /// target semantics.
  3542. ///
  3543. /// The value might be a vector of floats (or a complex number).
  3544. static bool IsSameFloatAfterCast(const APValue &value,
  3545. const llvm::fltSemantics &Src,
  3546. const llvm::fltSemantics &Tgt) {
  3547. if (value.isFloat())
  3548. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  3549. if (value.isVector()) {
  3550. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  3551. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  3552. return false;
  3553. return true;
  3554. }
  3555. assert(value.isComplexFloat());
  3556. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  3557. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  3558. }
  3559. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  3560. static bool IsZero(Sema &S, Expr *E) {
  3561. // Suppress cases where we are comparing against an enum constant.
  3562. if (const DeclRefExpr *DR =
  3563. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  3564. if (isa<EnumConstantDecl>(DR->getDecl()))
  3565. return false;
  3566. // Suppress cases where the '0' value is expanded from a macro.
  3567. if (E->getLocStart().isMacroID())
  3568. return false;
  3569. llvm::APSInt Value;
  3570. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  3571. }
  3572. static bool HasEnumType(Expr *E) {
  3573. // Strip off implicit integral promotions.
  3574. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3575. if (ICE->getCastKind() != CK_IntegralCast &&
  3576. ICE->getCastKind() != CK_NoOp)
  3577. break;
  3578. E = ICE->getSubExpr();
  3579. }
  3580. return E->getType()->isEnumeralType();
  3581. }
  3582. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  3583. BinaryOperatorKind op = E->getOpcode();
  3584. if (E->isValueDependent())
  3585. return;
  3586. if (op == BO_LT && IsZero(S, E->getRHS())) {
  3587. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3588. << "< 0" << "false" << HasEnumType(E->getLHS())
  3589. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3590. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  3591. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3592. << ">= 0" << "true" << HasEnumType(E->getLHS())
  3593. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3594. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  3595. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3596. << "0 >" << "false" << HasEnumType(E->getRHS())
  3597. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3598. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  3599. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3600. << "0 <=" << "true" << HasEnumType(E->getRHS())
  3601. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3602. }
  3603. }
  3604. /// Analyze the operands of the given comparison. Implements the
  3605. /// fallback case from AnalyzeComparison.
  3606. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  3607. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3608. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3609. }
  3610. /// \brief Implements -Wsign-compare.
  3611. ///
  3612. /// \param E the binary operator to check for warnings
  3613. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  3614. // The type the comparison is being performed in.
  3615. QualType T = E->getLHS()->getType();
  3616. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  3617. && "comparison with mismatched types");
  3618. // We don't do anything special if this isn't an unsigned integral
  3619. // comparison: we're only interested in integral comparisons, and
  3620. // signed comparisons only happen in cases we don't care to warn about.
  3621. //
  3622. // We also don't care about value-dependent expressions or expressions
  3623. // whose result is a constant.
  3624. if (!T->hasUnsignedIntegerRepresentation()
  3625. || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
  3626. return AnalyzeImpConvsInComparison(S, E);
  3627. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  3628. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  3629. // Check to see if one of the (unmodified) operands is of different
  3630. // signedness.
  3631. Expr *signedOperand, *unsignedOperand;
  3632. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  3633. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  3634. "unsigned comparison between two signed integer expressions?");
  3635. signedOperand = LHS;
  3636. unsignedOperand = RHS;
  3637. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  3638. signedOperand = RHS;
  3639. unsignedOperand = LHS;
  3640. } else {
  3641. CheckTrivialUnsignedComparison(S, E);
  3642. return AnalyzeImpConvsInComparison(S, E);
  3643. }
  3644. // Otherwise, calculate the effective range of the signed operand.
  3645. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  3646. // Go ahead and analyze implicit conversions in the operands. Note
  3647. // that we skip the implicit conversions on both sides.
  3648. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  3649. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  3650. // If the signed range is non-negative, -Wsign-compare won't fire,
  3651. // but we should still check for comparisons which are always true
  3652. // or false.
  3653. if (signedRange.NonNegative)
  3654. return CheckTrivialUnsignedComparison(S, E);
  3655. // For (in)equality comparisons, if the unsigned operand is a
  3656. // constant which cannot collide with a overflowed signed operand,
  3657. // then reinterpreting the signed operand as unsigned will not
  3658. // change the result of the comparison.
  3659. if (E->isEqualityOp()) {
  3660. unsigned comparisonWidth = S.Context.getIntWidth(T);
  3661. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  3662. // We should never be unable to prove that the unsigned operand is
  3663. // non-negative.
  3664. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  3665. if (unsignedRange.Width < comparisonWidth)
  3666. return;
  3667. }
  3668. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  3669. S.PDiag(diag::warn_mixed_sign_comparison)
  3670. << LHS->getType() << RHS->getType()
  3671. << LHS->getSourceRange() << RHS->getSourceRange());
  3672. }
  3673. /// Analyzes an attempt to assign the given value to a bitfield.
  3674. ///
  3675. /// Returns true if there was something fishy about the attempt.
  3676. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  3677. SourceLocation InitLoc) {
  3678. assert(Bitfield->isBitField());
  3679. if (Bitfield->isInvalidDecl())
  3680. return false;
  3681. // White-list bool bitfields.
  3682. if (Bitfield->getType()->isBooleanType())
  3683. return false;
  3684. // Ignore value- or type-dependent expressions.
  3685. if (Bitfield->getBitWidth()->isValueDependent() ||
  3686. Bitfield->getBitWidth()->isTypeDependent() ||
  3687. Init->isValueDependent() ||
  3688. Init->isTypeDependent())
  3689. return false;
  3690. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  3691. llvm::APSInt Value;
  3692. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  3693. return false;
  3694. unsigned OriginalWidth = Value.getBitWidth();
  3695. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  3696. if (OriginalWidth <= FieldWidth)
  3697. return false;
  3698. // Compute the value which the bitfield will contain.
  3699. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  3700. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  3701. // Check whether the stored value is equal to the original value.
  3702. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  3703. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  3704. return false;
  3705. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  3706. // therefore don't strictly fit into a signed bitfield of width 1.
  3707. if (FieldWidth == 1 && Value == 1)
  3708. return false;
  3709. std::string PrettyValue = Value.toString(10);
  3710. std::string PrettyTrunc = TruncatedValue.toString(10);
  3711. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  3712. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  3713. << Init->getSourceRange();
  3714. return true;
  3715. }
  3716. /// Analyze the given simple or compound assignment for warning-worthy
  3717. /// operations.
  3718. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  3719. // Just recurse on the LHS.
  3720. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3721. // We want to recurse on the RHS as normal unless we're assigning to
  3722. // a bitfield.
  3723. if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
  3724. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  3725. E->getOperatorLoc())) {
  3726. // Recurse, ignoring any implicit conversions on the RHS.
  3727. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  3728. E->getOperatorLoc());
  3729. }
  3730. }
  3731. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3732. }
  3733. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3734. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  3735. SourceLocation CContext, unsigned diag,
  3736. bool pruneControlFlow = false) {
  3737. if (pruneControlFlow) {
  3738. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3739. S.PDiag(diag)
  3740. << SourceType << T << E->getSourceRange()
  3741. << SourceRange(CContext));
  3742. return;
  3743. }
  3744. S.Diag(E->getExprLoc(), diag)
  3745. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  3746. }
  3747. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3748. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  3749. SourceLocation CContext, unsigned diag,
  3750. bool pruneControlFlow = false) {
  3751. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  3752. }
  3753. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  3754. /// cast wouldn't lose information.
  3755. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  3756. SourceLocation CContext) {
  3757. // Try to convert the literal exactly to an integer. If we can, don't warn.
  3758. bool isExact = false;
  3759. const llvm::APFloat &Value = FL->getValue();
  3760. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  3761. T->hasUnsignedIntegerRepresentation());
  3762. if (Value.convertToInteger(IntegerValue,
  3763. llvm::APFloat::rmTowardZero, &isExact)
  3764. == llvm::APFloat::opOK && isExact)
  3765. return;
  3766. SmallString<16> PrettySourceValue;
  3767. Value.toString(PrettySourceValue);
  3768. SmallString<16> PrettyTargetValue;
  3769. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  3770. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  3771. else
  3772. IntegerValue.toString(PrettyTargetValue);
  3773. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  3774. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  3775. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  3776. }
  3777. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  3778. if (!Range.Width) return "0";
  3779. llvm::APSInt ValueInRange = Value;
  3780. ValueInRange.setIsSigned(!Range.NonNegative);
  3781. ValueInRange = ValueInRange.trunc(Range.Width);
  3782. return ValueInRange.toString(10);
  3783. }
  3784. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  3785. SourceLocation CC, bool *ICContext = 0) {
  3786. if (E->isTypeDependent() || E->isValueDependent()) return;
  3787. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  3788. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  3789. if (Source == Target) return;
  3790. if (Target->isDependentType()) return;
  3791. // If the conversion context location is invalid don't complain. We also
  3792. // don't want to emit a warning if the issue occurs from the expansion of
  3793. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  3794. // delay this check as long as possible. Once we detect we are in that
  3795. // scenario, we just return.
  3796. if (CC.isInvalid())
  3797. return;
  3798. // Diagnose implicit casts to bool.
  3799. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  3800. if (isa<StringLiteral>(E))
  3801. // Warn on string literal to bool. Checks for string literals in logical
  3802. // expressions, for instances, assert(0 && "error here"), is prevented
  3803. // by a check in AnalyzeImplicitConversions().
  3804. return DiagnoseImpCast(S, E, T, CC,
  3805. diag::warn_impcast_string_literal_to_bool);
  3806. if (Source->isFunctionType()) {
  3807. // Warn on function to bool. Checks free functions and static member
  3808. // functions. Weakly imported functions are excluded from the check,
  3809. // since it's common to test their value to check whether the linker
  3810. // found a definition for them.
  3811. ValueDecl *D = 0;
  3812. if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
  3813. D = R->getDecl();
  3814. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  3815. D = M->getMemberDecl();
  3816. }
  3817. if (D && !D->isWeak()) {
  3818. if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
  3819. S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
  3820. << F << E->getSourceRange() << SourceRange(CC);
  3821. S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
  3822. << FixItHint::CreateInsertion(E->getExprLoc(), "&");
  3823. QualType ReturnType;
  3824. UnresolvedSet<4> NonTemplateOverloads;
  3825. S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
  3826. if (!ReturnType.isNull()
  3827. && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  3828. S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
  3829. << FixItHint::CreateInsertion(
  3830. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
  3831. return;
  3832. }
  3833. }
  3834. }
  3835. }
  3836. // Strip vector types.
  3837. if (isa<VectorType>(Source)) {
  3838. if (!isa<VectorType>(Target)) {
  3839. if (S.SourceMgr.isInSystemMacro(CC))
  3840. return;
  3841. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  3842. }
  3843. // If the vector cast is cast between two vectors of the same size, it is
  3844. // a bitcast, not a conversion.
  3845. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  3846. return;
  3847. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  3848. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  3849. }
  3850. // Strip complex types.
  3851. if (isa<ComplexType>(Source)) {
  3852. if (!isa<ComplexType>(Target)) {
  3853. if (S.SourceMgr.isInSystemMacro(CC))
  3854. return;
  3855. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  3856. }
  3857. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  3858. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  3859. }
  3860. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  3861. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  3862. // If the source is floating point...
  3863. if (SourceBT && SourceBT->isFloatingPoint()) {
  3864. // ...and the target is floating point...
  3865. if (TargetBT && TargetBT->isFloatingPoint()) {
  3866. // ...then warn if we're dropping FP rank.
  3867. // Builtin FP kinds are ordered by increasing FP rank.
  3868. if (SourceBT->getKind() > TargetBT->getKind()) {
  3869. // Don't warn about float constants that are precisely
  3870. // representable in the target type.
  3871. Expr::EvalResult result;
  3872. if (E->EvaluateAsRValue(result, S.Context)) {
  3873. // Value might be a float, a float vector, or a float complex.
  3874. if (IsSameFloatAfterCast(result.Val,
  3875. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  3876. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  3877. return;
  3878. }
  3879. if (S.SourceMgr.isInSystemMacro(CC))
  3880. return;
  3881. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  3882. }
  3883. return;
  3884. }
  3885. // If the target is integral, always warn.
  3886. if (TargetBT && TargetBT->isInteger()) {
  3887. if (S.SourceMgr.isInSystemMacro(CC))
  3888. return;
  3889. Expr *InnerE = E->IgnoreParenImpCasts();
  3890. // We also want to warn on, e.g., "int i = -1.234"
  3891. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  3892. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  3893. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  3894. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  3895. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  3896. } else {
  3897. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  3898. }
  3899. }
  3900. return;
  3901. }
  3902. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  3903. == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
  3904. && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
  3905. SourceLocation Loc = E->getSourceRange().getBegin();
  3906. if (Loc.isMacroID())
  3907. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  3908. if (!Loc.isMacroID() || CC.isMacroID())
  3909. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  3910. << T << clang::SourceRange(CC)
  3911. << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
  3912. }
  3913. if (!Source->isIntegerType() || !Target->isIntegerType())
  3914. return;
  3915. // TODO: remove this early return once the false positives for constant->bool
  3916. // in templates, macros, etc, are reduced or removed.
  3917. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  3918. return;
  3919. IntRange SourceRange = GetExprRange(S.Context, E);
  3920. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  3921. if (SourceRange.Width > TargetRange.Width) {
  3922. // If the source is a constant, use a default-on diagnostic.
  3923. // TODO: this should happen for bitfield stores, too.
  3924. llvm::APSInt Value(32);
  3925. if (E->isIntegerConstantExpr(Value, S.Context)) {
  3926. if (S.SourceMgr.isInSystemMacro(CC))
  3927. return;
  3928. std::string PrettySourceValue = Value.toString(10);
  3929. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  3930. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3931. S.PDiag(diag::warn_impcast_integer_precision_constant)
  3932. << PrettySourceValue << PrettyTargetValue
  3933. << E->getType() << T << E->getSourceRange()
  3934. << clang::SourceRange(CC));
  3935. return;
  3936. }
  3937. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  3938. if (S.SourceMgr.isInSystemMacro(CC))
  3939. return;
  3940. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  3941. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  3942. /* pruneControlFlow */ true);
  3943. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  3944. }
  3945. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  3946. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  3947. SourceRange.Width == TargetRange.Width)) {
  3948. if (S.SourceMgr.isInSystemMacro(CC))
  3949. return;
  3950. unsigned DiagID = diag::warn_impcast_integer_sign;
  3951. // Traditionally, gcc has warned about this under -Wsign-compare.
  3952. // We also want to warn about it in -Wconversion.
  3953. // So if -Wconversion is off, use a completely identical diagnostic
  3954. // in the sign-compare group.
  3955. // The conditional-checking code will
  3956. if (ICContext) {
  3957. DiagID = diag::warn_impcast_integer_sign_conditional;
  3958. *ICContext = true;
  3959. }
  3960. return DiagnoseImpCast(S, E, T, CC, DiagID);
  3961. }
  3962. // Diagnose conversions between different enumeration types.
  3963. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  3964. // type, to give us better diagnostics.
  3965. QualType SourceType = E->getType();
  3966. if (!S.getLangOpts().CPlusPlus) {
  3967. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  3968. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  3969. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  3970. SourceType = S.Context.getTypeDeclType(Enum);
  3971. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  3972. }
  3973. }
  3974. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  3975. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  3976. if ((SourceEnum->getDecl()->getIdentifier() ||
  3977. SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  3978. (TargetEnum->getDecl()->getIdentifier() ||
  3979. TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  3980. SourceEnum != TargetEnum) {
  3981. if (S.SourceMgr.isInSystemMacro(CC))
  3982. return;
  3983. return DiagnoseImpCast(S, E, SourceType, T, CC,
  3984. diag::warn_impcast_different_enum_types);
  3985. }
  3986. return;
  3987. }
  3988. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  3989. SourceLocation CC, QualType T);
  3990. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  3991. SourceLocation CC, bool &ICContext) {
  3992. E = E->IgnoreParenImpCasts();
  3993. if (isa<ConditionalOperator>(E))
  3994. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  3995. AnalyzeImplicitConversions(S, E, CC);
  3996. if (E->getType() != T)
  3997. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  3998. return;
  3999. }
  4000. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  4001. SourceLocation CC, QualType T) {
  4002. AnalyzeImplicitConversions(S, E->getCond(), CC);
  4003. bool Suspicious = false;
  4004. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  4005. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  4006. // If -Wconversion would have warned about either of the candidates
  4007. // for a signedness conversion to the context type...
  4008. if (!Suspicious) return;
  4009. // ...but it's currently ignored...
  4010. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  4011. CC))
  4012. return;
  4013. // ...then check whether it would have warned about either of the
  4014. // candidates for a signedness conversion to the condition type.
  4015. if (E->getType() == T) return;
  4016. Suspicious = false;
  4017. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  4018. E->getType(), CC, &Suspicious);
  4019. if (!Suspicious)
  4020. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  4021. E->getType(), CC, &Suspicious);
  4022. }
  4023. /// AnalyzeImplicitConversions - Find and report any interesting
  4024. /// implicit conversions in the given expression. There are a couple
  4025. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  4026. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  4027. QualType T = OrigE->getType();
  4028. Expr *E = OrigE->IgnoreParenImpCasts();
  4029. if (E->isTypeDependent() || E->isValueDependent())
  4030. return;
  4031. // For conditional operators, we analyze the arguments as if they
  4032. // were being fed directly into the output.
  4033. if (isa<ConditionalOperator>(E)) {
  4034. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  4035. CheckConditionalOperator(S, CO, CC, T);
  4036. return;
  4037. }
  4038. // Go ahead and check any implicit conversions we might have skipped.
  4039. // The non-canonical typecheck is just an optimization;
  4040. // CheckImplicitConversion will filter out dead implicit conversions.
  4041. if (E->getType() != T)
  4042. CheckImplicitConversion(S, E, T, CC);
  4043. // Now continue drilling into this expression.
  4044. // Skip past explicit casts.
  4045. if (isa<ExplicitCastExpr>(E)) {
  4046. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  4047. return AnalyzeImplicitConversions(S, E, CC);
  4048. }
  4049. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4050. // Do a somewhat different check with comparison operators.
  4051. if (BO->isComparisonOp())
  4052. return AnalyzeComparison(S, BO);
  4053. // And with simple assignments.
  4054. if (BO->getOpcode() == BO_Assign)
  4055. return AnalyzeAssignment(S, BO);
  4056. }
  4057. // These break the otherwise-useful invariant below. Fortunately,
  4058. // we don't really need to recurse into them, because any internal
  4059. // expressions should have been analyzed already when they were
  4060. // built into statements.
  4061. if (isa<StmtExpr>(E)) return;
  4062. // Don't descend into unevaluated contexts.
  4063. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  4064. // Now just recurse over the expression's children.
  4065. CC = E->getExprLoc();
  4066. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  4067. bool IsLogicalOperator = BO && BO->isLogicalOp();
  4068. for (Stmt::child_range I = E->children(); I; ++I) {
  4069. Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
  4070. if (!ChildExpr)
  4071. continue;
  4072. if (IsLogicalOperator &&
  4073. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  4074. // Ignore checking string literals that are in logical operators.
  4075. continue;
  4076. AnalyzeImplicitConversions(S, ChildExpr, CC);
  4077. }
  4078. }
  4079. } // end anonymous namespace
  4080. /// Diagnoses "dangerous" implicit conversions within the given
  4081. /// expression (which is a full expression). Implements -Wconversion
  4082. /// and -Wsign-compare.
  4083. ///
  4084. /// \param CC the "context" location of the implicit conversion, i.e.
  4085. /// the most location of the syntactic entity requiring the implicit
  4086. /// conversion
  4087. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  4088. // Don't diagnose in unevaluated contexts.
  4089. if (isUnevaluatedContext())
  4090. return;
  4091. // Don't diagnose for value- or type-dependent expressions.
  4092. if (E->isTypeDependent() || E->isValueDependent())
  4093. return;
  4094. // Check for array bounds violations in cases where the check isn't triggered
  4095. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  4096. // ArraySubscriptExpr is on the RHS of a variable initialization.
  4097. CheckArrayAccess(E);
  4098. // This is not the right CC for (e.g.) a variable initialization.
  4099. AnalyzeImplicitConversions(*this, E, CC);
  4100. }
  4101. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  4102. FieldDecl *BitField,
  4103. Expr *Init) {
  4104. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  4105. }
  4106. /// CheckParmsForFunctionDef - Check that the parameters of the given
  4107. /// function are appropriate for the definition of a function. This
  4108. /// takes care of any checks that cannot be performed on the
  4109. /// declaration itself, e.g., that the types of each of the function
  4110. /// parameters are complete.
  4111. bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
  4112. bool CheckParameterNames) {
  4113. bool HasInvalidParm = false;
  4114. for (; P != PEnd; ++P) {
  4115. ParmVarDecl *Param = *P;
  4116. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  4117. // function declarator that is part of a function definition of
  4118. // that function shall not have incomplete type.
  4119. //
  4120. // This is also C++ [dcl.fct]p6.
  4121. if (!Param->isInvalidDecl() &&
  4122. RequireCompleteType(Param->getLocation(), Param->getType(),
  4123. diag::err_typecheck_decl_incomplete_type)) {
  4124. Param->setInvalidDecl();
  4125. HasInvalidParm = true;
  4126. }
  4127. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  4128. // declaration of each parameter shall include an identifier.
  4129. if (CheckParameterNames &&
  4130. Param->getIdentifier() == 0 &&
  4131. !Param->isImplicit() &&
  4132. !getLangOpts().CPlusPlus)
  4133. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  4134. // C99 6.7.5.3p12:
  4135. // If the function declarator is not part of a definition of that
  4136. // function, parameters may have incomplete type and may use the [*]
  4137. // notation in their sequences of declarator specifiers to specify
  4138. // variable length array types.
  4139. QualType PType = Param->getOriginalType();
  4140. if (const ArrayType *AT = Context.getAsArrayType(PType)) {
  4141. if (AT->getSizeModifier() == ArrayType::Star) {
  4142. // FIXME: This diagnosic should point the '[*]' if source-location
  4143. // information is added for it.
  4144. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  4145. }
  4146. }
  4147. }
  4148. return HasInvalidParm;
  4149. }
  4150. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  4151. /// pointer cast increases the alignment requirements.
  4152. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  4153. // This is actually a lot of work to potentially be doing on every
  4154. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  4155. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  4156. TRange.getBegin())
  4157. == DiagnosticsEngine::Ignored)
  4158. return;
  4159. // Ignore dependent types.
  4160. if (T->isDependentType() || Op->getType()->isDependentType())
  4161. return;
  4162. // Require that the destination be a pointer type.
  4163. const PointerType *DestPtr = T->getAs<PointerType>();
  4164. if (!DestPtr) return;
  4165. // If the destination has alignment 1, we're done.
  4166. QualType DestPointee = DestPtr->getPointeeType();
  4167. if (DestPointee->isIncompleteType()) return;
  4168. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  4169. if (DestAlign.isOne()) return;
  4170. // Require that the source be a pointer type.
  4171. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  4172. if (!SrcPtr) return;
  4173. QualType SrcPointee = SrcPtr->getPointeeType();
  4174. // Whitelist casts from cv void*. We already implicitly
  4175. // whitelisted casts to cv void*, since they have alignment 1.
  4176. // Also whitelist casts involving incomplete types, which implicitly
  4177. // includes 'void'.
  4178. if (SrcPointee->isIncompleteType()) return;
  4179. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  4180. if (SrcAlign >= DestAlign) return;
  4181. Diag(TRange.getBegin(), diag::warn_cast_align)
  4182. << Op->getType() << T
  4183. << static_cast<unsigned>(SrcAlign.getQuantity())
  4184. << static_cast<unsigned>(DestAlign.getQuantity())
  4185. << TRange << Op->getSourceRange();
  4186. }
  4187. static const Type* getElementType(const Expr *BaseExpr) {
  4188. const Type* EltType = BaseExpr->getType().getTypePtr();
  4189. if (EltType->isAnyPointerType())
  4190. return EltType->getPointeeType().getTypePtr();
  4191. else if (EltType->isArrayType())
  4192. return EltType->getBaseElementTypeUnsafe();
  4193. return EltType;
  4194. }
  4195. /// \brief Check whether this array fits the idiom of a size-one tail padded
  4196. /// array member of a struct.
  4197. ///
  4198. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  4199. /// commonly used to emulate flexible arrays in C89 code.
  4200. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  4201. const NamedDecl *ND) {
  4202. if (Size != 1 || !ND) return false;
  4203. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  4204. if (!FD) return false;
  4205. // Don't consider sizes resulting from macro expansions or template argument
  4206. // substitution to form C89 tail-padded arrays.
  4207. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  4208. while (TInfo) {
  4209. TypeLoc TL = TInfo->getTypeLoc();
  4210. // Look through typedefs.
  4211. const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
  4212. if (TTL) {
  4213. const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
  4214. TInfo = TDL->getTypeSourceInfo();
  4215. continue;
  4216. }
  4217. ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
  4218. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  4219. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  4220. return false;
  4221. break;
  4222. }
  4223. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  4224. if (!RD) return false;
  4225. if (RD->isUnion()) return false;
  4226. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  4227. if (!CRD->isStandardLayout()) return false;
  4228. }
  4229. // See if this is the last field decl in the record.
  4230. const Decl *D = FD;
  4231. while ((D = D->getNextDeclInContext()))
  4232. if (isa<FieldDecl>(D))
  4233. return false;
  4234. return true;
  4235. }
  4236. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  4237. const ArraySubscriptExpr *ASE,
  4238. bool AllowOnePastEnd, bool IndexNegated) {
  4239. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  4240. if (IndexExpr->isValueDependent())
  4241. return;
  4242. const Type *EffectiveType = getElementType(BaseExpr);
  4243. BaseExpr = BaseExpr->IgnoreParenCasts();
  4244. const ConstantArrayType *ArrayTy =
  4245. Context.getAsConstantArrayType(BaseExpr->getType());
  4246. if (!ArrayTy)
  4247. return;
  4248. llvm::APSInt index;
  4249. if (!IndexExpr->EvaluateAsInt(index, Context))
  4250. return;
  4251. if (IndexNegated)
  4252. index = -index;
  4253. const NamedDecl *ND = NULL;
  4254. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4255. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4256. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4257. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4258. if (index.isUnsigned() || !index.isNegative()) {
  4259. llvm::APInt size = ArrayTy->getSize();
  4260. if (!size.isStrictlyPositive())
  4261. return;
  4262. const Type* BaseType = getElementType(BaseExpr);
  4263. if (BaseType != EffectiveType) {
  4264. // Make sure we're comparing apples to apples when comparing index to size
  4265. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  4266. uint64_t array_typesize = Context.getTypeSize(BaseType);
  4267. // Handle ptrarith_typesize being zero, such as when casting to void*
  4268. if (!ptrarith_typesize) ptrarith_typesize = 1;
  4269. if (ptrarith_typesize != array_typesize) {
  4270. // There's a cast to a different size type involved
  4271. uint64_t ratio = array_typesize / ptrarith_typesize;
  4272. // TODO: Be smarter about handling cases where array_typesize is not a
  4273. // multiple of ptrarith_typesize
  4274. if (ptrarith_typesize * ratio == array_typesize)
  4275. size *= llvm::APInt(size.getBitWidth(), ratio);
  4276. }
  4277. }
  4278. if (size.getBitWidth() > index.getBitWidth())
  4279. index = index.zext(size.getBitWidth());
  4280. else if (size.getBitWidth() < index.getBitWidth())
  4281. size = size.zext(index.getBitWidth());
  4282. // For array subscripting the index must be less than size, but for pointer
  4283. // arithmetic also allow the index (offset) to be equal to size since
  4284. // computing the next address after the end of the array is legal and
  4285. // commonly done e.g. in C++ iterators and range-based for loops.
  4286. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  4287. return;
  4288. // Also don't warn for arrays of size 1 which are members of some
  4289. // structure. These are often used to approximate flexible arrays in C89
  4290. // code.
  4291. if (IsTailPaddedMemberArray(*this, size, ND))
  4292. return;
  4293. // Suppress the warning if the subscript expression (as identified by the
  4294. // ']' location) and the index expression are both from macro expansions
  4295. // within a system header.
  4296. if (ASE) {
  4297. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  4298. ASE->getRBracketLoc());
  4299. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  4300. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  4301. IndexExpr->getLocStart());
  4302. if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
  4303. return;
  4304. }
  4305. }
  4306. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  4307. if (ASE)
  4308. DiagID = diag::warn_array_index_exceeds_bounds;
  4309. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4310. PDiag(DiagID) << index.toString(10, true)
  4311. << size.toString(10, true)
  4312. << (unsigned)size.getLimitedValue(~0U)
  4313. << IndexExpr->getSourceRange());
  4314. } else {
  4315. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  4316. if (!ASE) {
  4317. DiagID = diag::warn_ptr_arith_precedes_bounds;
  4318. if (index.isNegative()) index = -index;
  4319. }
  4320. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4321. PDiag(DiagID) << index.toString(10, true)
  4322. << IndexExpr->getSourceRange());
  4323. }
  4324. if (!ND) {
  4325. // Try harder to find a NamedDecl to point at in the note.
  4326. while (const ArraySubscriptExpr *ASE =
  4327. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  4328. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  4329. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4330. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4331. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4332. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4333. }
  4334. if (ND)
  4335. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  4336. PDiag(diag::note_array_index_out_of_bounds)
  4337. << ND->getDeclName());
  4338. }
  4339. void Sema::CheckArrayAccess(const Expr *expr) {
  4340. int AllowOnePastEnd = 0;
  4341. while (expr) {
  4342. expr = expr->IgnoreParenImpCasts();
  4343. switch (expr->getStmtClass()) {
  4344. case Stmt::ArraySubscriptExprClass: {
  4345. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  4346. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  4347. AllowOnePastEnd > 0);
  4348. return;
  4349. }
  4350. case Stmt::UnaryOperatorClass: {
  4351. // Only unwrap the * and & unary operators
  4352. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  4353. expr = UO->getSubExpr();
  4354. switch (UO->getOpcode()) {
  4355. case UO_AddrOf:
  4356. AllowOnePastEnd++;
  4357. break;
  4358. case UO_Deref:
  4359. AllowOnePastEnd--;
  4360. break;
  4361. default:
  4362. return;
  4363. }
  4364. break;
  4365. }
  4366. case Stmt::ConditionalOperatorClass: {
  4367. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  4368. if (const Expr *lhs = cond->getLHS())
  4369. CheckArrayAccess(lhs);
  4370. if (const Expr *rhs = cond->getRHS())
  4371. CheckArrayAccess(rhs);
  4372. return;
  4373. }
  4374. default:
  4375. return;
  4376. }
  4377. }
  4378. }
  4379. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  4380. namespace {
  4381. struct RetainCycleOwner {
  4382. RetainCycleOwner() : Variable(0), Indirect(false) {}
  4383. VarDecl *Variable;
  4384. SourceRange Range;
  4385. SourceLocation Loc;
  4386. bool Indirect;
  4387. void setLocsFrom(Expr *e) {
  4388. Loc = e->getExprLoc();
  4389. Range = e->getSourceRange();
  4390. }
  4391. };
  4392. }
  4393. /// Consider whether capturing the given variable can possibly lead to
  4394. /// a retain cycle.
  4395. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  4396. // In ARC, it's captured strongly iff the variable has __strong
  4397. // lifetime. In MRR, it's captured strongly if the variable is
  4398. // __block and has an appropriate type.
  4399. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4400. return false;
  4401. owner.Variable = var;
  4402. owner.setLocsFrom(ref);
  4403. return true;
  4404. }
  4405. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4406. while (true) {
  4407. e = e->IgnoreParens();
  4408. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  4409. switch (cast->getCastKind()) {
  4410. case CK_BitCast:
  4411. case CK_LValueBitCast:
  4412. case CK_LValueToRValue:
  4413. case CK_ARCReclaimReturnedObject:
  4414. e = cast->getSubExpr();
  4415. continue;
  4416. default:
  4417. return false;
  4418. }
  4419. }
  4420. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  4421. ObjCIvarDecl *ivar = ref->getDecl();
  4422. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4423. return false;
  4424. // Try to find a retain cycle in the base.
  4425. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  4426. return false;
  4427. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  4428. owner.Indirect = true;
  4429. return true;
  4430. }
  4431. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  4432. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  4433. if (!var) return false;
  4434. return considerVariable(var, ref, owner);
  4435. }
  4436. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  4437. if (member->isArrow()) return false;
  4438. // Don't count this as an indirect ownership.
  4439. e = member->getBase();
  4440. continue;
  4441. }
  4442. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  4443. // Only pay attention to pseudo-objects on property references.
  4444. ObjCPropertyRefExpr *pre
  4445. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  4446. ->IgnoreParens());
  4447. if (!pre) return false;
  4448. if (pre->isImplicitProperty()) return false;
  4449. ObjCPropertyDecl *property = pre->getExplicitProperty();
  4450. if (!property->isRetaining() &&
  4451. !(property->getPropertyIvarDecl() &&
  4452. property->getPropertyIvarDecl()->getType()
  4453. .getObjCLifetime() == Qualifiers::OCL_Strong))
  4454. return false;
  4455. owner.Indirect = true;
  4456. if (pre->isSuperReceiver()) {
  4457. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  4458. if (!owner.Variable)
  4459. return false;
  4460. owner.Loc = pre->getLocation();
  4461. owner.Range = pre->getSourceRange();
  4462. return true;
  4463. }
  4464. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  4465. ->getSourceExpr());
  4466. continue;
  4467. }
  4468. // Array ivars?
  4469. return false;
  4470. }
  4471. }
  4472. namespace {
  4473. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  4474. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  4475. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  4476. Variable(variable), Capturer(0) {}
  4477. VarDecl *Variable;
  4478. Expr *Capturer;
  4479. void VisitDeclRefExpr(DeclRefExpr *ref) {
  4480. if (ref->getDecl() == Variable && !Capturer)
  4481. Capturer = ref;
  4482. }
  4483. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  4484. if (Capturer) return;
  4485. Visit(ref->getBase());
  4486. if (Capturer && ref->isFreeIvar())
  4487. Capturer = ref;
  4488. }
  4489. void VisitBlockExpr(BlockExpr *block) {
  4490. // Look inside nested blocks
  4491. if (block->getBlockDecl()->capturesVariable(Variable))
  4492. Visit(block->getBlockDecl()->getBody());
  4493. }
  4494. };
  4495. }
  4496. /// Check whether the given argument is a block which captures a
  4497. /// variable.
  4498. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4499. assert(owner.Variable && owner.Loc.isValid());
  4500. e = e->IgnoreParenCasts();
  4501. BlockExpr *block = dyn_cast<BlockExpr>(e);
  4502. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  4503. return 0;
  4504. FindCaptureVisitor visitor(S.Context, owner.Variable);
  4505. visitor.Visit(block->getBlockDecl()->getBody());
  4506. return visitor.Capturer;
  4507. }
  4508. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  4509. RetainCycleOwner &owner) {
  4510. assert(capturer);
  4511. assert(owner.Variable && owner.Loc.isValid());
  4512. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  4513. << owner.Variable << capturer->getSourceRange();
  4514. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  4515. << owner.Indirect << owner.Range;
  4516. }
  4517. /// Check for a keyword selector that starts with the word 'add' or
  4518. /// 'set'.
  4519. static bool isSetterLikeSelector(Selector sel) {
  4520. if (sel.isUnarySelector()) return false;
  4521. StringRef str = sel.getNameForSlot(0);
  4522. while (!str.empty() && str.front() == '_') str = str.substr(1);
  4523. if (str.startswith("set"))
  4524. str = str.substr(3);
  4525. else if (str.startswith("add")) {
  4526. // Specially whitelist 'addOperationWithBlock:'.
  4527. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  4528. return false;
  4529. str = str.substr(3);
  4530. }
  4531. else
  4532. return false;
  4533. if (str.empty()) return true;
  4534. return !islower(str.front());
  4535. }
  4536. /// Check a message send to see if it's likely to cause a retain cycle.
  4537. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  4538. // Only check instance methods whose selector looks like a setter.
  4539. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  4540. return;
  4541. // Try to find a variable that the receiver is strongly owned by.
  4542. RetainCycleOwner owner;
  4543. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  4544. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  4545. return;
  4546. } else {
  4547. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  4548. owner.Variable = getCurMethodDecl()->getSelfDecl();
  4549. owner.Loc = msg->getSuperLoc();
  4550. owner.Range = msg->getSuperLoc();
  4551. }
  4552. // Check whether the receiver is captured by any of the arguments.
  4553. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  4554. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  4555. return diagnoseRetainCycle(*this, capturer, owner);
  4556. }
  4557. /// Check a property assign to see if it's likely to cause a retain cycle.
  4558. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  4559. RetainCycleOwner owner;
  4560. if (!findRetainCycleOwner(*this, receiver, owner))
  4561. return;
  4562. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  4563. diagnoseRetainCycle(*this, capturer, owner);
  4564. }
  4565. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  4566. QualType LHS, Expr *RHS) {
  4567. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  4568. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  4569. return false;
  4570. // strip off any implicit cast added to get to the one arc-specific
  4571. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4572. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4573. Diag(Loc, diag::warn_arc_retained_assign)
  4574. << (LT == Qualifiers::OCL_ExplicitNone) << 1
  4575. << RHS->getSourceRange();
  4576. return true;
  4577. }
  4578. RHS = cast->getSubExpr();
  4579. }
  4580. return false;
  4581. }
  4582. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  4583. Expr *LHS, Expr *RHS) {
  4584. QualType LHSType;
  4585. // PropertyRef on LHS type need be directly obtained from
  4586. // its declaration as it has a PsuedoType.
  4587. ObjCPropertyRefExpr *PRE
  4588. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  4589. if (PRE && !PRE->isImplicitProperty()) {
  4590. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4591. if (PD)
  4592. LHSType = PD->getType();
  4593. }
  4594. if (LHSType.isNull())
  4595. LHSType = LHS->getType();
  4596. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  4597. return;
  4598. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  4599. // FIXME. Check for other life times.
  4600. if (LT != Qualifiers::OCL_None)
  4601. return;
  4602. if (PRE) {
  4603. if (PRE->isImplicitProperty())
  4604. return;
  4605. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4606. if (!PD)
  4607. return;
  4608. unsigned Attributes = PD->getPropertyAttributes();
  4609. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  4610. // when 'assign' attribute was not explicitly specified
  4611. // by user, ignore it and rely on property type itself
  4612. // for lifetime info.
  4613. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  4614. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  4615. LHSType->isObjCRetainableType())
  4616. return;
  4617. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4618. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4619. Diag(Loc, diag::warn_arc_retained_property_assign)
  4620. << RHS->getSourceRange();
  4621. return;
  4622. }
  4623. RHS = cast->getSubExpr();
  4624. }
  4625. }
  4626. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  4627. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4628. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4629. Diag(Loc, diag::warn_arc_retained_assign)
  4630. << 0 << 0<< RHS->getSourceRange();
  4631. return;
  4632. }
  4633. RHS = cast->getSubExpr();
  4634. }
  4635. }
  4636. }
  4637. }
  4638. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  4639. namespace {
  4640. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  4641. SourceLocation StmtLoc,
  4642. const NullStmt *Body) {
  4643. // Do not warn if the body is a macro that expands to nothing, e.g:
  4644. //
  4645. // #define CALL(x)
  4646. // if (condition)
  4647. // CALL(0);
  4648. //
  4649. if (Body->hasLeadingEmptyMacro())
  4650. return false;
  4651. // Get line numbers of statement and body.
  4652. bool StmtLineInvalid;
  4653. unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
  4654. &StmtLineInvalid);
  4655. if (StmtLineInvalid)
  4656. return false;
  4657. bool BodyLineInvalid;
  4658. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  4659. &BodyLineInvalid);
  4660. if (BodyLineInvalid)
  4661. return false;
  4662. // Warn if null statement and body are on the same line.
  4663. if (StmtLine != BodyLine)
  4664. return false;
  4665. return true;
  4666. }
  4667. } // Unnamed namespace
  4668. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  4669. const Stmt *Body,
  4670. unsigned DiagID) {
  4671. // Since this is a syntactic check, don't emit diagnostic for template
  4672. // instantiations, this just adds noise.
  4673. if (CurrentInstantiationScope)
  4674. return;
  4675. // The body should be a null statement.
  4676. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4677. if (!NBody)
  4678. return;
  4679. // Do the usual checks.
  4680. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4681. return;
  4682. Diag(NBody->getSemiLoc(), DiagID);
  4683. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4684. }
  4685. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  4686. const Stmt *PossibleBody) {
  4687. assert(!CurrentInstantiationScope); // Ensured by caller
  4688. SourceLocation StmtLoc;
  4689. const Stmt *Body;
  4690. unsigned DiagID;
  4691. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  4692. StmtLoc = FS->getRParenLoc();
  4693. Body = FS->getBody();
  4694. DiagID = diag::warn_empty_for_body;
  4695. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  4696. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  4697. Body = WS->getBody();
  4698. DiagID = diag::warn_empty_while_body;
  4699. } else
  4700. return; // Neither `for' nor `while'.
  4701. // The body should be a null statement.
  4702. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4703. if (!NBody)
  4704. return;
  4705. // Skip expensive checks if diagnostic is disabled.
  4706. if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
  4707. DiagnosticsEngine::Ignored)
  4708. return;
  4709. // Do the usual checks.
  4710. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4711. return;
  4712. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  4713. // noise level low, emit diagnostics only if for/while is followed by a
  4714. // CompoundStmt, e.g.:
  4715. // for (int i = 0; i < n; i++);
  4716. // {
  4717. // a(i);
  4718. // }
  4719. // or if for/while is followed by a statement with more indentation
  4720. // than for/while itself:
  4721. // for (int i = 0; i < n; i++);
  4722. // a(i);
  4723. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  4724. if (!ProbableTypo) {
  4725. bool BodyColInvalid;
  4726. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  4727. PossibleBody->getLocStart(),
  4728. &BodyColInvalid);
  4729. if (BodyColInvalid)
  4730. return;
  4731. bool StmtColInvalid;
  4732. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  4733. S->getLocStart(),
  4734. &StmtColInvalid);
  4735. if (StmtColInvalid)
  4736. return;
  4737. if (BodyCol > StmtCol)
  4738. ProbableTypo = true;
  4739. }
  4740. if (ProbableTypo) {
  4741. Diag(NBody->getSemiLoc(), DiagID);
  4742. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4743. }
  4744. }
  4745. //===--- Layout compatibility ----------------------------------------------//
  4746. namespace {
  4747. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  4748. /// \brief Check if two enumeration types are layout-compatible.
  4749. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  4750. // C++11 [dcl.enum] p8:
  4751. // Two enumeration types are layout-compatible if they have the same
  4752. // underlying type.
  4753. return ED1->isComplete() && ED2->isComplete() &&
  4754. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  4755. }
  4756. /// \brief Check if two fields are layout-compatible.
  4757. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  4758. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  4759. return false;
  4760. if (Field1->isBitField() != Field2->isBitField())
  4761. return false;
  4762. if (Field1->isBitField()) {
  4763. // Make sure that the bit-fields are the same length.
  4764. unsigned Bits1 = Field1->getBitWidthValue(C);
  4765. unsigned Bits2 = Field2->getBitWidthValue(C);
  4766. if (Bits1 != Bits2)
  4767. return false;
  4768. }
  4769. return true;
  4770. }
  4771. /// \brief Check if two standard-layout structs are layout-compatible.
  4772. /// (C++11 [class.mem] p17)
  4773. bool isLayoutCompatibleStruct(ASTContext &C,
  4774. RecordDecl *RD1,
  4775. RecordDecl *RD2) {
  4776. // If both records are C++ classes, check that base classes match.
  4777. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  4778. // If one of records is a CXXRecordDecl we are in C++ mode,
  4779. // thus the other one is a CXXRecordDecl, too.
  4780. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  4781. // Check number of base classes.
  4782. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  4783. return false;
  4784. // Check the base classes.
  4785. for (CXXRecordDecl::base_class_const_iterator
  4786. Base1 = D1CXX->bases_begin(),
  4787. BaseEnd1 = D1CXX->bases_end(),
  4788. Base2 = D2CXX->bases_begin();
  4789. Base1 != BaseEnd1;
  4790. ++Base1, ++Base2) {
  4791. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  4792. return false;
  4793. }
  4794. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  4795. // If only RD2 is a C++ class, it should have zero base classes.
  4796. if (D2CXX->getNumBases() > 0)
  4797. return false;
  4798. }
  4799. // Check the fields.
  4800. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  4801. Field2End = RD2->field_end(),
  4802. Field1 = RD1->field_begin(),
  4803. Field1End = RD1->field_end();
  4804. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  4805. if (!isLayoutCompatible(C, *Field1, *Field2))
  4806. return false;
  4807. }
  4808. if (Field1 != Field1End || Field2 != Field2End)
  4809. return false;
  4810. return true;
  4811. }
  4812. /// \brief Check if two standard-layout unions are layout-compatible.
  4813. /// (C++11 [class.mem] p18)
  4814. bool isLayoutCompatibleUnion(ASTContext &C,
  4815. RecordDecl *RD1,
  4816. RecordDecl *RD2) {
  4817. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  4818. for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
  4819. Field2End = RD2->field_end();
  4820. Field2 != Field2End; ++Field2) {
  4821. UnmatchedFields.insert(*Field2);
  4822. }
  4823. for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
  4824. Field1End = RD1->field_end();
  4825. Field1 != Field1End; ++Field1) {
  4826. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  4827. I = UnmatchedFields.begin(),
  4828. E = UnmatchedFields.end();
  4829. for ( ; I != E; ++I) {
  4830. if (isLayoutCompatible(C, *Field1, *I)) {
  4831. bool Result = UnmatchedFields.erase(*I);
  4832. (void) Result;
  4833. assert(Result);
  4834. break;
  4835. }
  4836. }
  4837. if (I == E)
  4838. return false;
  4839. }
  4840. return UnmatchedFields.empty();
  4841. }
  4842. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  4843. if (RD1->isUnion() != RD2->isUnion())
  4844. return false;
  4845. if (RD1->isUnion())
  4846. return isLayoutCompatibleUnion(C, RD1, RD2);
  4847. else
  4848. return isLayoutCompatibleStruct(C, RD1, RD2);
  4849. }
  4850. /// \brief Check if two types are layout-compatible in C++11 sense.
  4851. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  4852. if (T1.isNull() || T2.isNull())
  4853. return false;
  4854. // C++11 [basic.types] p11:
  4855. // If two types T1 and T2 are the same type, then T1 and T2 are
  4856. // layout-compatible types.
  4857. if (C.hasSameType(T1, T2))
  4858. return true;
  4859. T1 = T1.getCanonicalType().getUnqualifiedType();
  4860. T2 = T2.getCanonicalType().getUnqualifiedType();
  4861. const Type::TypeClass TC1 = T1->getTypeClass();
  4862. const Type::TypeClass TC2 = T2->getTypeClass();
  4863. if (TC1 != TC2)
  4864. return false;
  4865. if (TC1 == Type::Enum) {
  4866. return isLayoutCompatible(C,
  4867. cast<EnumType>(T1)->getDecl(),
  4868. cast<EnumType>(T2)->getDecl());
  4869. } else if (TC1 == Type::Record) {
  4870. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  4871. return false;
  4872. return isLayoutCompatible(C,
  4873. cast<RecordType>(T1)->getDecl(),
  4874. cast<RecordType>(T2)->getDecl());
  4875. }
  4876. return false;
  4877. }
  4878. }
  4879. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  4880. namespace {
  4881. /// \brief Given a type tag expression find the type tag itself.
  4882. ///
  4883. /// \param TypeExpr Type tag expression, as it appears in user's code.
  4884. ///
  4885. /// \param VD Declaration of an identifier that appears in a type tag.
  4886. ///
  4887. /// \param MagicValue Type tag magic value.
  4888. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  4889. const ValueDecl **VD, uint64_t *MagicValue) {
  4890. while(true) {
  4891. if (!TypeExpr)
  4892. return false;
  4893. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  4894. switch (TypeExpr->getStmtClass()) {
  4895. case Stmt::UnaryOperatorClass: {
  4896. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  4897. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  4898. TypeExpr = UO->getSubExpr();
  4899. continue;
  4900. }
  4901. return false;
  4902. }
  4903. case Stmt::DeclRefExprClass: {
  4904. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  4905. *VD = DRE->getDecl();
  4906. return true;
  4907. }
  4908. case Stmt::IntegerLiteralClass: {
  4909. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  4910. llvm::APInt MagicValueAPInt = IL->getValue();
  4911. if (MagicValueAPInt.getActiveBits() <= 64) {
  4912. *MagicValue = MagicValueAPInt.getZExtValue();
  4913. return true;
  4914. } else
  4915. return false;
  4916. }
  4917. case Stmt::BinaryConditionalOperatorClass:
  4918. case Stmt::ConditionalOperatorClass: {
  4919. const AbstractConditionalOperator *ACO =
  4920. cast<AbstractConditionalOperator>(TypeExpr);
  4921. bool Result;
  4922. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  4923. if (Result)
  4924. TypeExpr = ACO->getTrueExpr();
  4925. else
  4926. TypeExpr = ACO->getFalseExpr();
  4927. continue;
  4928. }
  4929. return false;
  4930. }
  4931. case Stmt::BinaryOperatorClass: {
  4932. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  4933. if (BO->getOpcode() == BO_Comma) {
  4934. TypeExpr = BO->getRHS();
  4935. continue;
  4936. }
  4937. return false;
  4938. }
  4939. default:
  4940. return false;
  4941. }
  4942. }
  4943. }
  4944. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  4945. ///
  4946. /// \param TypeExpr Expression that specifies a type tag.
  4947. ///
  4948. /// \param MagicValues Registered magic values.
  4949. ///
  4950. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  4951. /// kind.
  4952. ///
  4953. /// \param TypeInfo Information about the corresponding C type.
  4954. ///
  4955. /// \returns true if the corresponding C type was found.
  4956. bool GetMatchingCType(
  4957. const IdentifierInfo *ArgumentKind,
  4958. const Expr *TypeExpr, const ASTContext &Ctx,
  4959. const llvm::DenseMap<Sema::TypeTagMagicValue,
  4960. Sema::TypeTagData> *MagicValues,
  4961. bool &FoundWrongKind,
  4962. Sema::TypeTagData &TypeInfo) {
  4963. FoundWrongKind = false;
  4964. // Variable declaration that has type_tag_for_datatype attribute.
  4965. const ValueDecl *VD = NULL;
  4966. uint64_t MagicValue;
  4967. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  4968. return false;
  4969. if (VD) {
  4970. for (specific_attr_iterator<TypeTagForDatatypeAttr>
  4971. I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
  4972. E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
  4973. I != E; ++I) {
  4974. if (I->getArgumentKind() != ArgumentKind) {
  4975. FoundWrongKind = true;
  4976. return false;
  4977. }
  4978. TypeInfo.Type = I->getMatchingCType();
  4979. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  4980. TypeInfo.MustBeNull = I->getMustBeNull();
  4981. return true;
  4982. }
  4983. return false;
  4984. }
  4985. if (!MagicValues)
  4986. return false;
  4987. llvm::DenseMap<Sema::TypeTagMagicValue,
  4988. Sema::TypeTagData>::const_iterator I =
  4989. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  4990. if (I == MagicValues->end())
  4991. return false;
  4992. TypeInfo = I->second;
  4993. return true;
  4994. }
  4995. } // unnamed namespace
  4996. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  4997. uint64_t MagicValue, QualType Type,
  4998. bool LayoutCompatible,
  4999. bool MustBeNull) {
  5000. if (!TypeTagForDatatypeMagicValues)
  5001. TypeTagForDatatypeMagicValues.reset(
  5002. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  5003. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  5004. (*TypeTagForDatatypeMagicValues)[Magic] =
  5005. TypeTagData(Type, LayoutCompatible, MustBeNull);
  5006. }
  5007. namespace {
  5008. bool IsSameCharType(QualType T1, QualType T2) {
  5009. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  5010. if (!BT1)
  5011. return false;
  5012. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  5013. if (!BT2)
  5014. return false;
  5015. BuiltinType::Kind T1Kind = BT1->getKind();
  5016. BuiltinType::Kind T2Kind = BT2->getKind();
  5017. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  5018. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  5019. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  5020. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  5021. }
  5022. } // unnamed namespace
  5023. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  5024. const Expr * const *ExprArgs) {
  5025. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  5026. bool IsPointerAttr = Attr->getIsPointer();
  5027. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  5028. bool FoundWrongKind;
  5029. TypeTagData TypeInfo;
  5030. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  5031. TypeTagForDatatypeMagicValues.get(),
  5032. FoundWrongKind, TypeInfo)) {
  5033. if (FoundWrongKind)
  5034. Diag(TypeTagExpr->getExprLoc(),
  5035. diag::warn_type_tag_for_datatype_wrong_kind)
  5036. << TypeTagExpr->getSourceRange();
  5037. return;
  5038. }
  5039. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  5040. if (IsPointerAttr) {
  5041. // Skip implicit cast of pointer to `void *' (as a function argument).
  5042. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  5043. if (ICE->getType()->isVoidPointerType())
  5044. ArgumentExpr = ICE->getSubExpr();
  5045. }
  5046. QualType ArgumentType = ArgumentExpr->getType();
  5047. // Passing a `void*' pointer shouldn't trigger a warning.
  5048. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  5049. return;
  5050. if (TypeInfo.MustBeNull) {
  5051. // Type tag with matching void type requires a null pointer.
  5052. if (!ArgumentExpr->isNullPointerConstant(Context,
  5053. Expr::NPC_ValueDependentIsNotNull)) {
  5054. Diag(ArgumentExpr->getExprLoc(),
  5055. diag::warn_type_safety_null_pointer_required)
  5056. << ArgumentKind->getName()
  5057. << ArgumentExpr->getSourceRange()
  5058. << TypeTagExpr->getSourceRange();
  5059. }
  5060. return;
  5061. }
  5062. QualType RequiredType = TypeInfo.Type;
  5063. if (IsPointerAttr)
  5064. RequiredType = Context.getPointerType(RequiredType);
  5065. bool mismatch = false;
  5066. if (!TypeInfo.LayoutCompatible) {
  5067. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  5068. // C++11 [basic.fundamental] p1:
  5069. // Plain char, signed char, and unsigned char are three distinct types.
  5070. //
  5071. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  5072. // char' depending on the current char signedness mode.
  5073. if (mismatch)
  5074. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  5075. RequiredType->getPointeeType())) ||
  5076. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  5077. mismatch = false;
  5078. } else
  5079. if (IsPointerAttr)
  5080. mismatch = !isLayoutCompatible(Context,
  5081. ArgumentType->getPointeeType(),
  5082. RequiredType->getPointeeType());
  5083. else
  5084. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  5085. if (mismatch)
  5086. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  5087. << ArgumentType << ArgumentKind->getName()
  5088. << TypeInfo.LayoutCompatible << RequiredType
  5089. << ArgumentExpr->getSourceRange()
  5090. << TypeTagExpr->getSourceRange();
  5091. }