SemaCast.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271
  1. //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for cast expressions, including
  10. // 1) C-style casts like '(int) x'
  11. // 2) C++ functional casts like 'int(x)'
  12. // 3) C++ named casts like 'static_cast<int>(x)'
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTStructuralEquivalence.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/RecordLayout.h"
  21. #include "clang/Basic/PartialDiagnostic.h"
  22. #include "clang/Basic/TargetInfo.h"
  23. #include "clang/Lex/Preprocessor.h"
  24. #include "clang/Sema/Initialization.h"
  25. #include "clang/Sema/SemaInternal.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include <set>
  28. using namespace clang;
  29. enum TryCastResult {
  30. TC_NotApplicable, ///< The cast method is not applicable.
  31. TC_Success, ///< The cast method is appropriate and successful.
  32. TC_Extension, ///< The cast method is appropriate and accepted as a
  33. ///< language extension.
  34. TC_Failed ///< The cast method is appropriate, but failed. A
  35. ///< diagnostic has been emitted.
  36. };
  37. static bool isValidCast(TryCastResult TCR) {
  38. return TCR == TC_Success || TCR == TC_Extension;
  39. }
  40. enum CastType {
  41. CT_Const, ///< const_cast
  42. CT_Static, ///< static_cast
  43. CT_Reinterpret, ///< reinterpret_cast
  44. CT_Dynamic, ///< dynamic_cast
  45. CT_CStyle, ///< (Type)expr
  46. CT_Functional, ///< Type(expr)
  47. CT_Addrspace ///< addrspace_cast
  48. };
  49. namespace {
  50. struct CastOperation {
  51. CastOperation(Sema &S, QualType destType, ExprResult src)
  52. : Self(S), SrcExpr(src), DestType(destType),
  53. ResultType(destType.getNonLValueExprType(S.Context)),
  54. ValueKind(Expr::getValueKindForType(destType)),
  55. Kind(CK_Dependent), IsARCUnbridgedCast(false) {
  56. // C++ [expr.type]/8.2.2:
  57. // If a pr-value initially has the type cv-T, where T is a
  58. // cv-unqualified non-class, non-array type, the type of the
  59. // expression is adjusted to T prior to any further analysis.
  60. if (!S.Context.getLangOpts().ObjC && !DestType->isRecordType() &&
  61. !DestType->isArrayType()) {
  62. DestType = DestType.getUnqualifiedType();
  63. }
  64. if (const BuiltinType *placeholder =
  65. src.get()->getType()->getAsPlaceholderType()) {
  66. PlaceholderKind = placeholder->getKind();
  67. } else {
  68. PlaceholderKind = (BuiltinType::Kind) 0;
  69. }
  70. }
  71. Sema &Self;
  72. ExprResult SrcExpr;
  73. QualType DestType;
  74. QualType ResultType;
  75. ExprValueKind ValueKind;
  76. CastKind Kind;
  77. BuiltinType::Kind PlaceholderKind;
  78. CXXCastPath BasePath;
  79. bool IsARCUnbridgedCast;
  80. SourceRange OpRange;
  81. SourceRange DestRange;
  82. // Top-level semantics-checking routines.
  83. void CheckConstCast();
  84. void CheckReinterpretCast();
  85. void CheckStaticCast();
  86. void CheckDynamicCast();
  87. void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
  88. void CheckCStyleCast();
  89. void CheckBuiltinBitCast();
  90. void CheckAddrspaceCast();
  91. void updatePartOfExplicitCastFlags(CastExpr *CE) {
  92. // Walk down from the CE to the OrigSrcExpr, and mark all immediate
  93. // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
  94. // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
  95. for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
  96. ICE->setIsPartOfExplicitCast(true);
  97. }
  98. /// Complete an apparently-successful cast operation that yields
  99. /// the given expression.
  100. ExprResult complete(CastExpr *castExpr) {
  101. // If this is an unbridged cast, wrap the result in an implicit
  102. // cast that yields the unbridged-cast placeholder type.
  103. if (IsARCUnbridgedCast) {
  104. castExpr = ImplicitCastExpr::Create(
  105. Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent,
  106. castExpr, nullptr, castExpr->getValueKind(),
  107. Self.CurFPFeatureOverrides());
  108. }
  109. updatePartOfExplicitCastFlags(castExpr);
  110. return castExpr;
  111. }
  112. // Internal convenience methods.
  113. /// Try to handle the given placeholder expression kind. Return
  114. /// true if the source expression has the appropriate placeholder
  115. /// kind. A placeholder can only be claimed once.
  116. bool claimPlaceholder(BuiltinType::Kind K) {
  117. if (PlaceholderKind != K) return false;
  118. PlaceholderKind = (BuiltinType::Kind) 0;
  119. return true;
  120. }
  121. bool isPlaceholder() const {
  122. return PlaceholderKind != 0;
  123. }
  124. bool isPlaceholder(BuiltinType::Kind K) const {
  125. return PlaceholderKind == K;
  126. }
  127. // Language specific cast restrictions for address spaces.
  128. void checkAddressSpaceCast(QualType SrcType, QualType DestType);
  129. void checkCastAlign() {
  130. Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
  131. }
  132. void checkObjCConversion(Sema::CheckedConversionKind CCK) {
  133. assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
  134. Expr *src = SrcExpr.get();
  135. if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
  136. Sema::ACR_unbridged)
  137. IsARCUnbridgedCast = true;
  138. SrcExpr = src;
  139. }
  140. /// Check for and handle non-overload placeholder expressions.
  141. void checkNonOverloadPlaceholders() {
  142. if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
  143. return;
  144. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  145. if (SrcExpr.isInvalid())
  146. return;
  147. PlaceholderKind = (BuiltinType::Kind) 0;
  148. }
  149. };
  150. void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,
  151. SourceLocation OpLoc) {
  152. if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {
  153. if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
  154. if (const auto *DestType = dyn_cast<PointerType>(ToType)) {
  155. if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) {
  156. S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. struct CheckNoDerefRAII {
  163. CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
  164. ~CheckNoDerefRAII() {
  165. if (!Op.SrcExpr.isInvalid())
  166. CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,
  167. Op.OpRange.getBegin());
  168. }
  169. CastOperation &Op;
  170. };
  171. }
  172. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
  173. QualType DestType);
  174. // The Try functions attempt a specific way of casting. If they succeed, they
  175. // return TC_Success. If their way of casting is not appropriate for the given
  176. // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
  177. // to emit if no other way succeeds. If their way of casting is appropriate but
  178. // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
  179. // they emit a specialized diagnostic.
  180. // All diagnostics returned by these functions must expect the same three
  181. // arguments:
  182. // %0: Cast Type (a value from the CastType enumeration)
  183. // %1: Source Type
  184. // %2: Destination Type
  185. static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  186. QualType DestType, bool CStyle,
  187. CastKind &Kind,
  188. CXXCastPath &BasePath,
  189. unsigned &msg);
  190. static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
  191. QualType DestType, bool CStyle,
  192. SourceRange OpRange,
  193. unsigned &msg,
  194. CastKind &Kind,
  195. CXXCastPath &BasePath);
  196. static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
  197. QualType DestType, bool CStyle,
  198. SourceRange OpRange,
  199. unsigned &msg,
  200. CastKind &Kind,
  201. CXXCastPath &BasePath);
  202. static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
  203. CanQualType DestType, bool CStyle,
  204. SourceRange OpRange,
  205. QualType OrigSrcType,
  206. QualType OrigDestType, unsigned &msg,
  207. CastKind &Kind,
  208. CXXCastPath &BasePath);
  209. static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
  210. QualType SrcType,
  211. QualType DestType,bool CStyle,
  212. SourceRange OpRange,
  213. unsigned &msg,
  214. CastKind &Kind,
  215. CXXCastPath &BasePath);
  216. static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
  217. QualType DestType,
  218. Sema::CheckedConversionKind CCK,
  219. SourceRange OpRange,
  220. unsigned &msg, CastKind &Kind,
  221. bool ListInitialization);
  222. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  223. QualType DestType,
  224. Sema::CheckedConversionKind CCK,
  225. SourceRange OpRange,
  226. unsigned &msg, CastKind &Kind,
  227. CXXCastPath &BasePath,
  228. bool ListInitialization);
  229. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  230. QualType DestType, bool CStyle,
  231. unsigned &msg);
  232. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  233. QualType DestType, bool CStyle,
  234. SourceRange OpRange, unsigned &msg,
  235. CastKind &Kind);
  236. static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
  237. QualType DestType, bool CStyle,
  238. unsigned &msg, CastKind &Kind);
  239. /// ActOnCXXNamedCast - Parse
  240. /// {dynamic,static,reinterpret,const,addrspace}_cast's.
  241. ExprResult
  242. Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  243. SourceLocation LAngleBracketLoc, Declarator &D,
  244. SourceLocation RAngleBracketLoc,
  245. SourceLocation LParenLoc, Expr *E,
  246. SourceLocation RParenLoc) {
  247. assert(!D.isInvalidType());
  248. TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
  249. if (D.isInvalidType())
  250. return ExprError();
  251. if (getLangOpts().CPlusPlus) {
  252. // Check that there are no default arguments (C++ only).
  253. CheckExtraCXXDefaultArguments(D);
  254. }
  255. return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
  256. SourceRange(LAngleBracketLoc, RAngleBracketLoc),
  257. SourceRange(LParenLoc, RParenLoc));
  258. }
  259. ExprResult
  260. Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  261. TypeSourceInfo *DestTInfo, Expr *E,
  262. SourceRange AngleBrackets, SourceRange Parens) {
  263. ExprResult Ex = E;
  264. QualType DestType = DestTInfo->getType();
  265. // If the type is dependent, we won't do the semantic analysis now.
  266. bool TypeDependent =
  267. DestType->isDependentType() || Ex.get()->isTypeDependent();
  268. CastOperation Op(*this, DestType, E);
  269. Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
  270. Op.DestRange = AngleBrackets;
  271. switch (Kind) {
  272. default: llvm_unreachable("Unknown C++ cast!");
  273. case tok::kw_addrspace_cast:
  274. if (!TypeDependent) {
  275. Op.CheckAddrspaceCast();
  276. if (Op.SrcExpr.isInvalid())
  277. return ExprError();
  278. }
  279. return Op.complete(CXXAddrspaceCastExpr::Create(
  280. Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  281. DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));
  282. case tok::kw_const_cast:
  283. if (!TypeDependent) {
  284. Op.CheckConstCast();
  285. if (Op.SrcExpr.isInvalid())
  286. return ExprError();
  287. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  288. }
  289. return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
  290. Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
  291. OpLoc, Parens.getEnd(),
  292. AngleBrackets));
  293. case tok::kw_dynamic_cast: {
  294. // dynamic_cast is not supported in C++ for OpenCL.
  295. if (getLangOpts().OpenCLCPlusPlus) {
  296. return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
  297. << "dynamic_cast");
  298. }
  299. if (!TypeDependent) {
  300. Op.CheckDynamicCast();
  301. if (Op.SrcExpr.isInvalid())
  302. return ExprError();
  303. }
  304. return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
  305. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  306. &Op.BasePath, DestTInfo,
  307. OpLoc, Parens.getEnd(),
  308. AngleBrackets));
  309. }
  310. case tok::kw_reinterpret_cast: {
  311. if (!TypeDependent) {
  312. Op.CheckReinterpretCast();
  313. if (Op.SrcExpr.isInvalid())
  314. return ExprError();
  315. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  316. }
  317. return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
  318. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  319. nullptr, DestTInfo, OpLoc,
  320. Parens.getEnd(),
  321. AngleBrackets));
  322. }
  323. case tok::kw_static_cast: {
  324. if (!TypeDependent) {
  325. Op.CheckStaticCast();
  326. if (Op.SrcExpr.isInvalid())
  327. return ExprError();
  328. DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
  329. }
  330. return Op.complete(CXXStaticCastExpr::Create(
  331. Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  332. &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc,
  333. Parens.getEnd(), AngleBrackets));
  334. }
  335. }
  336. }
  337. ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
  338. ExprResult Operand,
  339. SourceLocation RParenLoc) {
  340. assert(!D.isInvalidType());
  341. TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
  342. if (D.isInvalidType())
  343. return ExprError();
  344. return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
  345. }
  346. ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
  347. TypeSourceInfo *TSI, Expr *Operand,
  348. SourceLocation RParenLoc) {
  349. CastOperation Op(*this, TSI->getType(), Operand);
  350. Op.OpRange = SourceRange(KWLoc, RParenLoc);
  351. TypeLoc TL = TSI->getTypeLoc();
  352. Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
  353. if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
  354. Op.CheckBuiltinBitCast();
  355. if (Op.SrcExpr.isInvalid())
  356. return ExprError();
  357. }
  358. BuiltinBitCastExpr *BCE =
  359. new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
  360. Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
  361. return Op.complete(BCE);
  362. }
  363. /// Try to diagnose a failed overloaded cast. Returns true if
  364. /// diagnostics were emitted.
  365. static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
  366. SourceRange range, Expr *src,
  367. QualType destType,
  368. bool listInitialization) {
  369. switch (CT) {
  370. // These cast kinds don't consider user-defined conversions.
  371. case CT_Const:
  372. case CT_Reinterpret:
  373. case CT_Dynamic:
  374. case CT_Addrspace:
  375. return false;
  376. // These do.
  377. case CT_Static:
  378. case CT_CStyle:
  379. case CT_Functional:
  380. break;
  381. }
  382. QualType srcType = src->getType();
  383. if (!destType->isRecordType() && !srcType->isRecordType())
  384. return false;
  385. InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
  386. InitializationKind initKind
  387. = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
  388. range, listInitialization)
  389. : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
  390. listInitialization)
  391. : InitializationKind::CreateCast(/*type range?*/ range);
  392. InitializationSequence sequence(S, entity, initKind, src);
  393. assert(sequence.Failed() && "initialization succeeded on second try?");
  394. switch (sequence.getFailureKind()) {
  395. default: return false;
  396. case InitializationSequence::FK_ConstructorOverloadFailed:
  397. case InitializationSequence::FK_UserConversionOverloadFailed:
  398. break;
  399. }
  400. OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
  401. unsigned msg = 0;
  402. OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
  403. switch (sequence.getFailedOverloadResult()) {
  404. case OR_Success: llvm_unreachable("successful failed overload");
  405. case OR_No_Viable_Function:
  406. if (candidates.empty())
  407. msg = diag::err_ovl_no_conversion_in_cast;
  408. else
  409. msg = diag::err_ovl_no_viable_conversion_in_cast;
  410. howManyCandidates = OCD_AllCandidates;
  411. break;
  412. case OR_Ambiguous:
  413. msg = diag::err_ovl_ambiguous_conversion_in_cast;
  414. howManyCandidates = OCD_AmbiguousCandidates;
  415. break;
  416. case OR_Deleted:
  417. msg = diag::err_ovl_deleted_conversion_in_cast;
  418. howManyCandidates = OCD_ViableCandidates;
  419. break;
  420. }
  421. candidates.NoteCandidates(
  422. PartialDiagnosticAt(range.getBegin(),
  423. S.PDiag(msg) << CT << srcType << destType << range
  424. << src->getSourceRange()),
  425. S, howManyCandidates, src);
  426. return true;
  427. }
  428. /// Diagnose a failed cast.
  429. static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
  430. SourceRange opRange, Expr *src, QualType destType,
  431. bool listInitialization) {
  432. if (msg == diag::err_bad_cxx_cast_generic &&
  433. tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
  434. listInitialization))
  435. return;
  436. S.Diag(opRange.getBegin(), msg) << castType
  437. << src->getType() << destType << opRange << src->getSourceRange();
  438. // Detect if both types are (ptr to) class, and note any incompleteness.
  439. int DifferentPtrness = 0;
  440. QualType From = destType;
  441. if (auto Ptr = From->getAs<PointerType>()) {
  442. From = Ptr->getPointeeType();
  443. DifferentPtrness++;
  444. }
  445. QualType To = src->getType();
  446. if (auto Ptr = To->getAs<PointerType>()) {
  447. To = Ptr->getPointeeType();
  448. DifferentPtrness--;
  449. }
  450. if (!DifferentPtrness) {
  451. auto RecFrom = From->getAs<RecordType>();
  452. auto RecTo = To->getAs<RecordType>();
  453. if (RecFrom && RecTo) {
  454. auto DeclFrom = RecFrom->getAsCXXRecordDecl();
  455. if (!DeclFrom->isCompleteDefinition())
  456. S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom;
  457. auto DeclTo = RecTo->getAsCXXRecordDecl();
  458. if (!DeclTo->isCompleteDefinition())
  459. S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo;
  460. }
  461. }
  462. }
  463. namespace {
  464. /// The kind of unwrapping we did when determining whether a conversion casts
  465. /// away constness.
  466. enum CastAwayConstnessKind {
  467. /// The conversion does not cast away constness.
  468. CACK_None = 0,
  469. /// We unwrapped similar types.
  470. CACK_Similar = 1,
  471. /// We unwrapped dissimilar types with similar representations (eg, a pointer
  472. /// versus an Objective-C object pointer).
  473. CACK_SimilarKind = 2,
  474. /// We unwrapped representationally-unrelated types, such as a pointer versus
  475. /// a pointer-to-member.
  476. CACK_Incoherent = 3,
  477. };
  478. }
  479. /// Unwrap one level of types for CastsAwayConstness.
  480. ///
  481. /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
  482. /// both types, provided that they're both pointer-like or array-like. Unlike
  483. /// the Sema function, doesn't care if the unwrapped pieces are related.
  484. ///
  485. /// This function may remove additional levels as necessary for correctness:
  486. /// the resulting T1 is unwrapped sufficiently that it is never an array type,
  487. /// so that its qualifiers can be directly compared to those of T2 (which will
  488. /// have the combined set of qualifiers from all indermediate levels of T2),
  489. /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
  490. /// with those from T2.
  491. static CastAwayConstnessKind
  492. unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
  493. enum { None, Ptr, MemPtr, BlockPtr, Array };
  494. auto Classify = [](QualType T) {
  495. if (T->isAnyPointerType()) return Ptr;
  496. if (T->isMemberPointerType()) return MemPtr;
  497. if (T->isBlockPointerType()) return BlockPtr;
  498. // We somewhat-arbitrarily don't look through VLA types here. This is at
  499. // least consistent with the behavior of UnwrapSimilarTypes.
  500. if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
  501. return None;
  502. };
  503. auto Unwrap = [&](QualType T) {
  504. if (auto *AT = Context.getAsArrayType(T))
  505. return AT->getElementType();
  506. return T->getPointeeType();
  507. };
  508. CastAwayConstnessKind Kind;
  509. if (T2->isReferenceType()) {
  510. // Special case: if the destination type is a reference type, unwrap it as
  511. // the first level. (The source will have been an lvalue expression in this
  512. // case, so there is no corresponding "reference to" in T1 to remove.) This
  513. // simulates removing a "pointer to" from both sides.
  514. T2 = T2->getPointeeType();
  515. Kind = CastAwayConstnessKind::CACK_Similar;
  516. } else if (Context.UnwrapSimilarTypes(T1, T2)) {
  517. Kind = CastAwayConstnessKind::CACK_Similar;
  518. } else {
  519. // Try unwrapping mismatching levels.
  520. int T1Class = Classify(T1);
  521. if (T1Class == None)
  522. return CastAwayConstnessKind::CACK_None;
  523. int T2Class = Classify(T2);
  524. if (T2Class == None)
  525. return CastAwayConstnessKind::CACK_None;
  526. T1 = Unwrap(T1);
  527. T2 = Unwrap(T2);
  528. Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
  529. : CastAwayConstnessKind::CACK_Incoherent;
  530. }
  531. // We've unwrapped at least one level. If the resulting T1 is a (possibly
  532. // multidimensional) array type, any qualifier on any matching layer of
  533. // T2 is considered to correspond to T1. Decompose down to the element
  534. // type of T1 so that we can compare properly.
  535. while (true) {
  536. Context.UnwrapSimilarArrayTypes(T1, T2);
  537. if (Classify(T1) != Array)
  538. break;
  539. auto T2Class = Classify(T2);
  540. if (T2Class == None)
  541. break;
  542. if (T2Class != Array)
  543. Kind = CastAwayConstnessKind::CACK_Incoherent;
  544. else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
  545. Kind = CastAwayConstnessKind::CACK_SimilarKind;
  546. T1 = Unwrap(T1);
  547. T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
  548. }
  549. return Kind;
  550. }
  551. /// Check if the pointer conversion from SrcType to DestType casts away
  552. /// constness as defined in C++ [expr.const.cast]. This is used by the cast
  553. /// checkers. Both arguments must denote pointer (possibly to member) types.
  554. ///
  555. /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
  556. /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
  557. static CastAwayConstnessKind
  558. CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
  559. bool CheckCVR, bool CheckObjCLifetime,
  560. QualType *TheOffendingSrcType = nullptr,
  561. QualType *TheOffendingDestType = nullptr,
  562. Qualifiers *CastAwayQualifiers = nullptr) {
  563. // If the only checking we care about is for Objective-C lifetime qualifiers,
  564. // and we're not in ObjC mode, there's nothing to check.
  565. if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
  566. return CastAwayConstnessKind::CACK_None;
  567. if (!DestType->isReferenceType()) {
  568. assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
  569. SrcType->isBlockPointerType()) &&
  570. "Source type is not pointer or pointer to member.");
  571. assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
  572. DestType->isBlockPointerType()) &&
  573. "Destination type is not pointer or pointer to member.");
  574. }
  575. QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
  576. UnwrappedDestType = Self.Context.getCanonicalType(DestType);
  577. // Find the qualifiers. We only care about cvr-qualifiers for the
  578. // purpose of this check, because other qualifiers (address spaces,
  579. // Objective-C GC, etc.) are part of the type's identity.
  580. QualType PrevUnwrappedSrcType = UnwrappedSrcType;
  581. QualType PrevUnwrappedDestType = UnwrappedDestType;
  582. auto WorstKind = CastAwayConstnessKind::CACK_Similar;
  583. bool AllConstSoFar = true;
  584. while (auto Kind = unwrapCastAwayConstnessLevel(
  585. Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
  586. // Track the worst kind of unwrap we needed to do before we found a
  587. // problem.
  588. if (Kind > WorstKind)
  589. WorstKind = Kind;
  590. // Determine the relevant qualifiers at this level.
  591. Qualifiers SrcQuals, DestQuals;
  592. Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
  593. Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
  594. // We do not meaningfully track object const-ness of Objective-C object
  595. // types. Remove const from the source type if either the source or
  596. // the destination is an Objective-C object type.
  597. if (UnwrappedSrcType->isObjCObjectType() ||
  598. UnwrappedDestType->isObjCObjectType())
  599. SrcQuals.removeConst();
  600. if (CheckCVR) {
  601. Qualifiers SrcCvrQuals =
  602. Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
  603. Qualifiers DestCvrQuals =
  604. Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
  605. if (SrcCvrQuals != DestCvrQuals) {
  606. if (CastAwayQualifiers)
  607. *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
  608. // If we removed a cvr-qualifier, this is casting away 'constness'.
  609. if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
  610. if (TheOffendingSrcType)
  611. *TheOffendingSrcType = PrevUnwrappedSrcType;
  612. if (TheOffendingDestType)
  613. *TheOffendingDestType = PrevUnwrappedDestType;
  614. return WorstKind;
  615. }
  616. // If any prior level was not 'const', this is also casting away
  617. // 'constness'. We noted the outermost type missing a 'const' already.
  618. if (!AllConstSoFar)
  619. return WorstKind;
  620. }
  621. }
  622. if (CheckObjCLifetime &&
  623. !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
  624. return WorstKind;
  625. // If we found our first non-const-qualified type, this may be the place
  626. // where things start to go wrong.
  627. if (AllConstSoFar && !DestQuals.hasConst()) {
  628. AllConstSoFar = false;
  629. if (TheOffendingSrcType)
  630. *TheOffendingSrcType = PrevUnwrappedSrcType;
  631. if (TheOffendingDestType)
  632. *TheOffendingDestType = PrevUnwrappedDestType;
  633. }
  634. PrevUnwrappedSrcType = UnwrappedSrcType;
  635. PrevUnwrappedDestType = UnwrappedDestType;
  636. }
  637. return CastAwayConstnessKind::CACK_None;
  638. }
  639. static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
  640. unsigned &DiagID) {
  641. switch (CACK) {
  642. case CastAwayConstnessKind::CACK_None:
  643. llvm_unreachable("did not cast away constness");
  644. case CastAwayConstnessKind::CACK_Similar:
  645. // FIXME: Accept these as an extension too?
  646. case CastAwayConstnessKind::CACK_SimilarKind:
  647. DiagID = diag::err_bad_cxx_cast_qualifiers_away;
  648. return TC_Failed;
  649. case CastAwayConstnessKind::CACK_Incoherent:
  650. DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
  651. return TC_Extension;
  652. }
  653. llvm_unreachable("unexpected cast away constness kind");
  654. }
  655. /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
  656. /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
  657. /// checked downcasts in class hierarchies.
  658. void CastOperation::CheckDynamicCast() {
  659. CheckNoDerefRAII NoderefCheck(*this);
  660. if (ValueKind == VK_PRValue)
  661. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  662. else if (isPlaceholder())
  663. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  664. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  665. return;
  666. QualType OrigSrcType = SrcExpr.get()->getType();
  667. QualType DestType = Self.Context.getCanonicalType(this->DestType);
  668. // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
  669. // or "pointer to cv void".
  670. QualType DestPointee;
  671. const PointerType *DestPointer = DestType->getAs<PointerType>();
  672. const ReferenceType *DestReference = nullptr;
  673. if (DestPointer) {
  674. DestPointee = DestPointer->getPointeeType();
  675. } else if ((DestReference = DestType->getAs<ReferenceType>())) {
  676. DestPointee = DestReference->getPointeeType();
  677. } else {
  678. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
  679. << this->DestType << DestRange;
  680. SrcExpr = ExprError();
  681. return;
  682. }
  683. const RecordType *DestRecord = DestPointee->getAs<RecordType>();
  684. if (DestPointee->isVoidType()) {
  685. assert(DestPointer && "Reference to void is not possible");
  686. } else if (DestRecord) {
  687. if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
  688. diag::err_bad_cast_incomplete,
  689. DestRange)) {
  690. SrcExpr = ExprError();
  691. return;
  692. }
  693. } else {
  694. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  695. << DestPointee.getUnqualifiedType() << DestRange;
  696. SrcExpr = ExprError();
  697. return;
  698. }
  699. // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
  700. // complete class type, [...]. If T is an lvalue reference type, v shall be
  701. // an lvalue of a complete class type, [...]. If T is an rvalue reference
  702. // type, v shall be an expression having a complete class type, [...]
  703. QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
  704. QualType SrcPointee;
  705. if (DestPointer) {
  706. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  707. SrcPointee = SrcPointer->getPointeeType();
  708. } else {
  709. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
  710. << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();
  711. SrcExpr = ExprError();
  712. return;
  713. }
  714. } else if (DestReference->isLValueReferenceType()) {
  715. if (!SrcExpr.get()->isLValue()) {
  716. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
  717. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  718. }
  719. SrcPointee = SrcType;
  720. } else {
  721. // If we're dynamic_casting from a prvalue to an rvalue reference, we need
  722. // to materialize the prvalue before we bind the reference to it.
  723. if (SrcExpr.get()->isPRValue())
  724. SrcExpr = Self.CreateMaterializeTemporaryExpr(
  725. SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
  726. SrcPointee = SrcType;
  727. }
  728. const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
  729. if (SrcRecord) {
  730. if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
  731. diag::err_bad_cast_incomplete,
  732. SrcExpr.get())) {
  733. SrcExpr = ExprError();
  734. return;
  735. }
  736. } else {
  737. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  738. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  739. SrcExpr = ExprError();
  740. return;
  741. }
  742. assert((DestPointer || DestReference) &&
  743. "Bad destination non-ptr/ref slipped through.");
  744. assert((DestRecord || DestPointee->isVoidType()) &&
  745. "Bad destination pointee slipped through.");
  746. assert(SrcRecord && "Bad source pointee slipped through.");
  747. // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
  748. if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
  749. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
  750. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  751. SrcExpr = ExprError();
  752. return;
  753. }
  754. // C++ 5.2.7p3: If the type of v is the same as the required result type,
  755. // [except for cv].
  756. if (DestRecord == SrcRecord) {
  757. Kind = CK_NoOp;
  758. return;
  759. }
  760. // C++ 5.2.7p5
  761. // Upcasts are resolved statically.
  762. if (DestRecord &&
  763. Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
  764. if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
  765. OpRange.getBegin(), OpRange,
  766. &BasePath)) {
  767. SrcExpr = ExprError();
  768. return;
  769. }
  770. Kind = CK_DerivedToBase;
  771. return;
  772. }
  773. // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
  774. const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
  775. assert(SrcDecl && "Definition missing");
  776. if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
  777. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
  778. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  779. SrcExpr = ExprError();
  780. }
  781. // dynamic_cast is not available with -fno-rtti.
  782. // As an exception, dynamic_cast to void* is available because it doesn't
  783. // use RTTI.
  784. if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
  785. Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
  786. SrcExpr = ExprError();
  787. return;
  788. }
  789. // Warns when dynamic_cast is used with RTTI data disabled.
  790. if (!Self.getLangOpts().RTTIData) {
  791. bool MicrosoftABI =
  792. Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
  793. bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() ==
  794. DiagnosticOptions::MSVC;
  795. if (MicrosoftABI || !DestPointee->isVoidType())
  796. Self.Diag(OpRange.getBegin(),
  797. diag::warn_no_dynamic_cast_with_rtti_disabled)
  798. << isClangCL;
  799. }
  800. // Done. Everything else is run-time checks.
  801. Kind = CK_Dynamic;
  802. }
  803. /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
  804. /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
  805. /// like this:
  806. /// const char *str = "literal";
  807. /// legacy_function(const_cast\<char*\>(str));
  808. void CastOperation::CheckConstCast() {
  809. CheckNoDerefRAII NoderefCheck(*this);
  810. if (ValueKind == VK_PRValue)
  811. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  812. else if (isPlaceholder())
  813. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  814. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  815. return;
  816. unsigned msg = diag::err_bad_cxx_cast_generic;
  817. auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
  818. if (TCR != TC_Success && msg != 0) {
  819. Self.Diag(OpRange.getBegin(), msg) << CT_Const
  820. << SrcExpr.get()->getType() << DestType << OpRange;
  821. }
  822. if (!isValidCast(TCR))
  823. SrcExpr = ExprError();
  824. }
  825. void CastOperation::CheckAddrspaceCast() {
  826. unsigned msg = diag::err_bad_cxx_cast_generic;
  827. auto TCR =
  828. TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);
  829. if (TCR != TC_Success && msg != 0) {
  830. Self.Diag(OpRange.getBegin(), msg)
  831. << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;
  832. }
  833. if (!isValidCast(TCR))
  834. SrcExpr = ExprError();
  835. }
  836. /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
  837. /// or downcast between respective pointers or references.
  838. static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
  839. QualType DestType,
  840. SourceRange OpRange) {
  841. QualType SrcType = SrcExpr->getType();
  842. // When casting from pointer or reference, get pointee type; use original
  843. // type otherwise.
  844. const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
  845. const CXXRecordDecl *SrcRD =
  846. SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
  847. // Examining subobjects for records is only possible if the complete and
  848. // valid definition is available. Also, template instantiation is not
  849. // allowed here.
  850. if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
  851. return;
  852. const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
  853. if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
  854. return;
  855. enum {
  856. ReinterpretUpcast,
  857. ReinterpretDowncast
  858. } ReinterpretKind;
  859. CXXBasePaths BasePaths;
  860. if (SrcRD->isDerivedFrom(DestRD, BasePaths))
  861. ReinterpretKind = ReinterpretUpcast;
  862. else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
  863. ReinterpretKind = ReinterpretDowncast;
  864. else
  865. return;
  866. bool VirtualBase = true;
  867. bool NonZeroOffset = false;
  868. for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
  869. E = BasePaths.end();
  870. I != E; ++I) {
  871. const CXXBasePath &Path = *I;
  872. CharUnits Offset = CharUnits::Zero();
  873. bool IsVirtual = false;
  874. for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
  875. IElem != EElem; ++IElem) {
  876. IsVirtual = IElem->Base->isVirtual();
  877. if (IsVirtual)
  878. break;
  879. const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
  880. assert(BaseRD && "Base type should be a valid unqualified class type");
  881. // Don't check if any base has invalid declaration or has no definition
  882. // since it has no layout info.
  883. const CXXRecordDecl *Class = IElem->Class,
  884. *ClassDefinition = Class->getDefinition();
  885. if (Class->isInvalidDecl() || !ClassDefinition ||
  886. !ClassDefinition->isCompleteDefinition())
  887. return;
  888. const ASTRecordLayout &DerivedLayout =
  889. Self.Context.getASTRecordLayout(Class);
  890. Offset += DerivedLayout.getBaseClassOffset(BaseRD);
  891. }
  892. if (!IsVirtual) {
  893. // Don't warn if any path is a non-virtually derived base at offset zero.
  894. if (Offset.isZero())
  895. return;
  896. // Offset makes sense only for non-virtual bases.
  897. else
  898. NonZeroOffset = true;
  899. }
  900. VirtualBase = VirtualBase && IsVirtual;
  901. }
  902. (void) NonZeroOffset; // Silence set but not used warning.
  903. assert((VirtualBase || NonZeroOffset) &&
  904. "Should have returned if has non-virtual base with zero offset");
  905. QualType BaseType =
  906. ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
  907. QualType DerivedType =
  908. ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
  909. SourceLocation BeginLoc = OpRange.getBegin();
  910. Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
  911. << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
  912. << OpRange;
  913. Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
  914. << int(ReinterpretKind)
  915. << FixItHint::CreateReplacement(BeginLoc, "static_cast");
  916. }
  917. static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType,
  918. ASTContext &Context) {
  919. if (SrcType->isPointerType() && DestType->isPointerType())
  920. return true;
  921. // Allow integral type mismatch if their size are equal.
  922. if (SrcType->isIntegralType(Context) && DestType->isIntegralType(Context))
  923. if (Context.getTypeInfoInChars(SrcType).Width ==
  924. Context.getTypeInfoInChars(DestType).Width)
  925. return true;
  926. return Context.hasSameUnqualifiedType(SrcType, DestType);
  927. }
  928. static bool checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr,
  929. QualType DestType) {
  930. if (Self.Diags.isIgnored(diag::warn_cast_function_type,
  931. SrcExpr.get()->getExprLoc()))
  932. return true;
  933. QualType SrcType = SrcExpr.get()->getType();
  934. const FunctionType *SrcFTy = nullptr;
  935. const FunctionType *DstFTy = nullptr;
  936. if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) &&
  937. DestType->isFunctionPointerType()) ||
  938. (SrcType->isMemberFunctionPointerType() &&
  939. DestType->isMemberFunctionPointerType())) {
  940. SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>();
  941. DstFTy = DestType->getPointeeType()->castAs<FunctionType>();
  942. } else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) {
  943. SrcFTy = SrcType->castAs<FunctionType>();
  944. DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>();
  945. } else {
  946. return true;
  947. }
  948. assert(SrcFTy && DstFTy);
  949. auto IsVoidVoid = [](const FunctionType *T) {
  950. if (!T->getReturnType()->isVoidType())
  951. return false;
  952. if (const auto *PT = T->getAs<FunctionProtoType>())
  953. return !PT->isVariadic() && PT->getNumParams() == 0;
  954. return false;
  955. };
  956. // Skip if either function type is void(*)(void)
  957. if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy))
  958. return true;
  959. // Check return type.
  960. if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(),
  961. Self.Context))
  962. return false;
  963. // Check if either has unspecified number of parameters
  964. if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType())
  965. return true;
  966. // Check parameter types.
  967. const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy);
  968. const auto *DstFPTy = cast<FunctionProtoType>(DstFTy);
  969. // In a cast involving function types with a variable argument list only the
  970. // types of initial arguments that are provided are considered.
  971. unsigned NumParams = SrcFPTy->getNumParams();
  972. unsigned DstNumParams = DstFPTy->getNumParams();
  973. if (NumParams > DstNumParams) {
  974. if (!DstFPTy->isVariadic())
  975. return false;
  976. NumParams = DstNumParams;
  977. } else if (NumParams < DstNumParams) {
  978. if (!SrcFPTy->isVariadic())
  979. return false;
  980. }
  981. for (unsigned i = 0; i < NumParams; ++i)
  982. if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i),
  983. DstFPTy->getParamType(i), Self.Context))
  984. return false;
  985. return true;
  986. }
  987. /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
  988. /// valid.
  989. /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
  990. /// like this:
  991. /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
  992. void CastOperation::CheckReinterpretCast() {
  993. if (ValueKind == VK_PRValue && !isPlaceholder(BuiltinType::Overload))
  994. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  995. else
  996. checkNonOverloadPlaceholders();
  997. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  998. return;
  999. unsigned msg = diag::err_bad_cxx_cast_generic;
  1000. TryCastResult tcr =
  1001. TryReinterpretCast(Self, SrcExpr, DestType,
  1002. /*CStyle*/false, OpRange, msg, Kind);
  1003. if (tcr != TC_Success && msg != 0) {
  1004. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  1005. return;
  1006. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1007. //FIXME: &f<int>; is overloaded and resolvable
  1008. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
  1009. << OverloadExpr::find(SrcExpr.get()).Expression->getName()
  1010. << DestType << OpRange;
  1011. Self.NoteAllOverloadCandidates(SrcExpr.get());
  1012. } else {
  1013. diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
  1014. DestType, /*listInitialization=*/false);
  1015. }
  1016. }
  1017. if (isValidCast(tcr)) {
  1018. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  1019. checkObjCConversion(Sema::CCK_OtherCast);
  1020. DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
  1021. if (!checkCastFunctionType(Self, SrcExpr, DestType))
  1022. Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
  1023. << SrcExpr.get()->getType() << DestType << OpRange;
  1024. } else {
  1025. SrcExpr = ExprError();
  1026. }
  1027. }
  1028. /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
  1029. /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
  1030. /// implicit conversions explicit and getting rid of data loss warnings.
  1031. void CastOperation::CheckStaticCast() {
  1032. CheckNoDerefRAII NoderefCheck(*this);
  1033. if (isPlaceholder()) {
  1034. checkNonOverloadPlaceholders();
  1035. if (SrcExpr.isInvalid())
  1036. return;
  1037. }
  1038. // This test is outside everything else because it's the only case where
  1039. // a non-lvalue-reference target type does not lead to decay.
  1040. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  1041. if (DestType->isVoidType()) {
  1042. Kind = CK_ToVoid;
  1043. if (claimPlaceholder(BuiltinType::Overload)) {
  1044. Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
  1045. false, // Decay Function to ptr
  1046. true, // Complain
  1047. OpRange, DestType, diag::err_bad_static_cast_overload);
  1048. if (SrcExpr.isInvalid())
  1049. return;
  1050. }
  1051. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  1052. return;
  1053. }
  1054. if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
  1055. !isPlaceholder(BuiltinType::Overload)) {
  1056. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  1057. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  1058. return;
  1059. }
  1060. unsigned msg = diag::err_bad_cxx_cast_generic;
  1061. TryCastResult tcr
  1062. = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
  1063. Kind, BasePath, /*ListInitialization=*/false);
  1064. if (tcr != TC_Success && msg != 0) {
  1065. if (SrcExpr.isInvalid())
  1066. return;
  1067. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1068. OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
  1069. Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
  1070. << oe->getName() << DestType << OpRange
  1071. << oe->getQualifierLoc().getSourceRange();
  1072. Self.NoteAllOverloadCandidates(SrcExpr.get());
  1073. } else {
  1074. diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
  1075. /*listInitialization=*/false);
  1076. }
  1077. }
  1078. if (isValidCast(tcr)) {
  1079. if (Kind == CK_BitCast)
  1080. checkCastAlign();
  1081. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
  1082. checkObjCConversion(Sema::CCK_OtherCast);
  1083. } else {
  1084. SrcExpr = ExprError();
  1085. }
  1086. }
  1087. static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
  1088. auto *SrcPtrType = SrcType->getAs<PointerType>();
  1089. if (!SrcPtrType)
  1090. return false;
  1091. auto *DestPtrType = DestType->getAs<PointerType>();
  1092. if (!DestPtrType)
  1093. return false;
  1094. return SrcPtrType->getPointeeType().getAddressSpace() !=
  1095. DestPtrType->getPointeeType().getAddressSpace();
  1096. }
  1097. /// TryStaticCast - Check if a static cast can be performed, and do so if
  1098. /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
  1099. /// and casting away constness.
  1100. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  1101. QualType DestType,
  1102. Sema::CheckedConversionKind CCK,
  1103. SourceRange OpRange, unsigned &msg,
  1104. CastKind &Kind, CXXCastPath &BasePath,
  1105. bool ListInitialization) {
  1106. // Determine whether we have the semantics of a C-style cast.
  1107. bool CStyle
  1108. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  1109. // The order the tests is not entirely arbitrary. There is one conversion
  1110. // that can be handled in two different ways. Given:
  1111. // struct A {};
  1112. // struct B : public A {
  1113. // B(); B(const A&);
  1114. // };
  1115. // const A &a = B();
  1116. // the cast static_cast<const B&>(a) could be seen as either a static
  1117. // reference downcast, or an explicit invocation of the user-defined
  1118. // conversion using B's conversion constructor.
  1119. // DR 427 specifies that the downcast is to be applied here.
  1120. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  1121. // Done outside this function.
  1122. TryCastResult tcr;
  1123. // C++ 5.2.9p5, reference downcast.
  1124. // See the function for details.
  1125. // DR 427 specifies that this is to be applied before paragraph 2.
  1126. tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
  1127. OpRange, msg, Kind, BasePath);
  1128. if (tcr != TC_NotApplicable)
  1129. return tcr;
  1130. // C++11 [expr.static.cast]p3:
  1131. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
  1132. // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  1133. tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
  1134. BasePath, msg);
  1135. if (tcr != TC_NotApplicable)
  1136. return tcr;
  1137. // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
  1138. // [...] if the declaration "T t(e);" is well-formed, [...].
  1139. tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
  1140. Kind, ListInitialization);
  1141. if (SrcExpr.isInvalid())
  1142. return TC_Failed;
  1143. if (tcr != TC_NotApplicable)
  1144. return tcr;
  1145. // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
  1146. // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
  1147. // conversions, subject to further restrictions.
  1148. // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
  1149. // of qualification conversions impossible. (In C++20, adding an array bound
  1150. // would be the reverse of a qualification conversion, but adding permission
  1151. // to add an array bound in a static_cast is a wording oversight.)
  1152. // In the CStyle case, the earlier attempt to const_cast should have taken
  1153. // care of reverse qualification conversions.
  1154. QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
  1155. // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
  1156. // converted to an integral type. [...] A value of a scoped enumeration type
  1157. // can also be explicitly converted to a floating-point type [...].
  1158. if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
  1159. if (Enum->getDecl()->isScoped()) {
  1160. if (DestType->isBooleanType()) {
  1161. Kind = CK_IntegralToBoolean;
  1162. return TC_Success;
  1163. } else if (DestType->isIntegralType(Self.Context)) {
  1164. Kind = CK_IntegralCast;
  1165. return TC_Success;
  1166. } else if (DestType->isRealFloatingType()) {
  1167. Kind = CK_IntegralToFloating;
  1168. return TC_Success;
  1169. }
  1170. }
  1171. }
  1172. // Reverse integral promotion/conversion. All such conversions are themselves
  1173. // again integral promotions or conversions and are thus already handled by
  1174. // p2 (TryDirectInitialization above).
  1175. // (Note: any data loss warnings should be suppressed.)
  1176. // The exception is the reverse of enum->integer, i.e. integer->enum (and
  1177. // enum->enum). See also C++ 5.2.9p7.
  1178. // The same goes for reverse floating point promotion/conversion and
  1179. // floating-integral conversions. Again, only floating->enum is relevant.
  1180. if (DestType->isEnumeralType()) {
  1181. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  1182. diag::err_bad_cast_incomplete)) {
  1183. SrcExpr = ExprError();
  1184. return TC_Failed;
  1185. }
  1186. if (SrcType->isIntegralOrEnumerationType()) {
  1187. // [expr.static.cast]p10 If the enumeration type has a fixed underlying
  1188. // type, the value is first converted to that type by integral conversion
  1189. const EnumType *Enum = DestType->getAs<EnumType>();
  1190. Kind = Enum->getDecl()->isFixed() &&
  1191. Enum->getDecl()->getIntegerType()->isBooleanType()
  1192. ? CK_IntegralToBoolean
  1193. : CK_IntegralCast;
  1194. return TC_Success;
  1195. } else if (SrcType->isRealFloatingType()) {
  1196. Kind = CK_FloatingToIntegral;
  1197. return TC_Success;
  1198. }
  1199. }
  1200. // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
  1201. // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
  1202. tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
  1203. Kind, BasePath);
  1204. if (tcr != TC_NotApplicable)
  1205. return tcr;
  1206. // Reverse member pointer conversion. C++ 4.11 specifies member pointer
  1207. // conversion. C++ 5.2.9p9 has additional information.
  1208. // DR54's access restrictions apply here also.
  1209. tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
  1210. OpRange, msg, Kind, BasePath);
  1211. if (tcr != TC_NotApplicable)
  1212. return tcr;
  1213. // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
  1214. // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
  1215. // just the usual constness stuff.
  1216. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  1217. QualType SrcPointee = SrcPointer->getPointeeType();
  1218. if (SrcPointee->isVoidType()) {
  1219. if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
  1220. QualType DestPointee = DestPointer->getPointeeType();
  1221. if (DestPointee->isIncompleteOrObjectType()) {
  1222. // This is definitely the intended conversion, but it might fail due
  1223. // to a qualifier violation. Note that we permit Objective-C lifetime
  1224. // and GC qualifier mismatches here.
  1225. if (!CStyle) {
  1226. Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
  1227. Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
  1228. DestPointeeQuals.removeObjCGCAttr();
  1229. DestPointeeQuals.removeObjCLifetime();
  1230. SrcPointeeQuals.removeObjCGCAttr();
  1231. SrcPointeeQuals.removeObjCLifetime();
  1232. if (DestPointeeQuals != SrcPointeeQuals &&
  1233. !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
  1234. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1235. return TC_Failed;
  1236. }
  1237. }
  1238. Kind = IsAddressSpaceConversion(SrcType, DestType)
  1239. ? CK_AddressSpaceConversion
  1240. : CK_BitCast;
  1241. return TC_Success;
  1242. }
  1243. // Microsoft permits static_cast from 'pointer-to-void' to
  1244. // 'pointer-to-function'.
  1245. if (!CStyle && Self.getLangOpts().MSVCCompat &&
  1246. DestPointee->isFunctionType()) {
  1247. Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
  1248. Kind = CK_BitCast;
  1249. return TC_Success;
  1250. }
  1251. }
  1252. else if (DestType->isObjCObjectPointerType()) {
  1253. // allow both c-style cast and static_cast of objective-c pointers as
  1254. // they are pervasive.
  1255. Kind = CK_CPointerToObjCPointerCast;
  1256. return TC_Success;
  1257. }
  1258. else if (CStyle && DestType->isBlockPointerType()) {
  1259. // allow c-style cast of void * to block pointers.
  1260. Kind = CK_AnyPointerToBlockPointerCast;
  1261. return TC_Success;
  1262. }
  1263. }
  1264. }
  1265. // Allow arbitrary objective-c pointer conversion with static casts.
  1266. if (SrcType->isObjCObjectPointerType() &&
  1267. DestType->isObjCObjectPointerType()) {
  1268. Kind = CK_BitCast;
  1269. return TC_Success;
  1270. }
  1271. // Allow ns-pointer to cf-pointer conversion in either direction
  1272. // with static casts.
  1273. if (!CStyle &&
  1274. Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
  1275. return TC_Success;
  1276. // See if it looks like the user is trying to convert between
  1277. // related record types, and select a better diagnostic if so.
  1278. if (auto SrcPointer = SrcType->getAs<PointerType>())
  1279. if (auto DestPointer = DestType->getAs<PointerType>())
  1280. if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
  1281. DestPointer->getPointeeType()->getAs<RecordType>())
  1282. msg = diag::err_bad_cxx_cast_unrelated_class;
  1283. if (SrcType->isMatrixType() && DestType->isMatrixType()) {
  1284. if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) {
  1285. SrcExpr = ExprError();
  1286. return TC_Failed;
  1287. }
  1288. return TC_Success;
  1289. }
  1290. // We tried everything. Everything! Nothing works! :-(
  1291. return TC_NotApplicable;
  1292. }
  1293. /// Tests whether a conversion according to N2844 is valid.
  1294. TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  1295. QualType DestType, bool CStyle,
  1296. CastKind &Kind, CXXCastPath &BasePath,
  1297. unsigned &msg) {
  1298. // C++11 [expr.static.cast]p3:
  1299. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
  1300. // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  1301. const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
  1302. if (!R)
  1303. return TC_NotApplicable;
  1304. if (!SrcExpr->isGLValue())
  1305. return TC_NotApplicable;
  1306. // Because we try the reference downcast before this function, from now on
  1307. // this is the only cast possibility, so we issue an error if we fail now.
  1308. // FIXME: Should allow casting away constness if CStyle.
  1309. QualType FromType = SrcExpr->getType();
  1310. QualType ToType = R->getPointeeType();
  1311. if (CStyle) {
  1312. FromType = FromType.getUnqualifiedType();
  1313. ToType = ToType.getUnqualifiedType();
  1314. }
  1315. Sema::ReferenceConversions RefConv;
  1316. Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
  1317. SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
  1318. if (RefResult != Sema::Ref_Compatible) {
  1319. if (CStyle || RefResult == Sema::Ref_Incompatible)
  1320. return TC_NotApplicable;
  1321. // Diagnose types which are reference-related but not compatible here since
  1322. // we can provide better diagnostics. In these cases forwarding to
  1323. // [expr.static.cast]p4 should never result in a well-formed cast.
  1324. msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
  1325. : diag::err_bad_rvalue_to_rvalue_cast;
  1326. return TC_Failed;
  1327. }
  1328. if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
  1329. Kind = CK_DerivedToBase;
  1330. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1331. /*DetectVirtual=*/true);
  1332. if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
  1333. R->getPointeeType(), Paths))
  1334. return TC_NotApplicable;
  1335. Self.BuildBasePathArray(Paths, BasePath);
  1336. } else
  1337. Kind = CK_NoOp;
  1338. return TC_Success;
  1339. }
  1340. /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
  1341. TryCastResult
  1342. TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
  1343. bool CStyle, SourceRange OpRange,
  1344. unsigned &msg, CastKind &Kind,
  1345. CXXCastPath &BasePath) {
  1346. // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
  1347. // cast to type "reference to cv2 D", where D is a class derived from B,
  1348. // if a valid standard conversion from "pointer to D" to "pointer to B"
  1349. // exists, cv2 >= cv1, and B is not a virtual base class of D.
  1350. // In addition, DR54 clarifies that the base must be accessible in the
  1351. // current context. Although the wording of DR54 only applies to the pointer
  1352. // variant of this rule, the intent is clearly for it to apply to the this
  1353. // conversion as well.
  1354. const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
  1355. if (!DestReference) {
  1356. return TC_NotApplicable;
  1357. }
  1358. bool RValueRef = DestReference->isRValueReferenceType();
  1359. if (!RValueRef && !SrcExpr->isLValue()) {
  1360. // We know the left side is an lvalue reference, so we can suggest a reason.
  1361. msg = diag::err_bad_cxx_cast_rvalue;
  1362. return TC_NotApplicable;
  1363. }
  1364. QualType DestPointee = DestReference->getPointeeType();
  1365. // FIXME: If the source is a prvalue, we should issue a warning (because the
  1366. // cast always has undefined behavior), and for AST consistency, we should
  1367. // materialize a temporary.
  1368. return TryStaticDowncast(Self,
  1369. Self.Context.getCanonicalType(SrcExpr->getType()),
  1370. Self.Context.getCanonicalType(DestPointee), CStyle,
  1371. OpRange, SrcExpr->getType(), DestType, msg, Kind,
  1372. BasePath);
  1373. }
  1374. /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
  1375. TryCastResult
  1376. TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
  1377. bool CStyle, SourceRange OpRange,
  1378. unsigned &msg, CastKind &Kind,
  1379. CXXCastPath &BasePath) {
  1380. // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
  1381. // type, can be converted to an rvalue of type "pointer to cv2 D", where D
  1382. // is a class derived from B, if a valid standard conversion from "pointer
  1383. // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
  1384. // class of D.
  1385. // In addition, DR54 clarifies that the base must be accessible in the
  1386. // current context.
  1387. const PointerType *DestPointer = DestType->getAs<PointerType>();
  1388. if (!DestPointer) {
  1389. return TC_NotApplicable;
  1390. }
  1391. const PointerType *SrcPointer = SrcType->getAs<PointerType>();
  1392. if (!SrcPointer) {
  1393. msg = diag::err_bad_static_cast_pointer_nonpointer;
  1394. return TC_NotApplicable;
  1395. }
  1396. return TryStaticDowncast(Self,
  1397. Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
  1398. Self.Context.getCanonicalType(DestPointer->getPointeeType()),
  1399. CStyle, OpRange, SrcType, DestType, msg, Kind,
  1400. BasePath);
  1401. }
  1402. /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
  1403. /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
  1404. /// DestType is possible and allowed.
  1405. TryCastResult
  1406. TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
  1407. bool CStyle, SourceRange OpRange, QualType OrigSrcType,
  1408. QualType OrigDestType, unsigned &msg,
  1409. CastKind &Kind, CXXCastPath &BasePath) {
  1410. // We can only work with complete types. But don't complain if it doesn't work
  1411. if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
  1412. !Self.isCompleteType(OpRange.getBegin(), DestType))
  1413. return TC_NotApplicable;
  1414. // Downcast can only happen in class hierarchies, so we need classes.
  1415. if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
  1416. return TC_NotApplicable;
  1417. }
  1418. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1419. /*DetectVirtual=*/true);
  1420. if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
  1421. return TC_NotApplicable;
  1422. }
  1423. // Target type does derive from source type. Now we're serious. If an error
  1424. // appears now, it's not ignored.
  1425. // This may not be entirely in line with the standard. Take for example:
  1426. // struct A {};
  1427. // struct B : virtual A {
  1428. // B(A&);
  1429. // };
  1430. //
  1431. // void f()
  1432. // {
  1433. // (void)static_cast<const B&>(*((A*)0));
  1434. // }
  1435. // As far as the standard is concerned, p5 does not apply (A is virtual), so
  1436. // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
  1437. // However, both GCC and Comeau reject this example, and accepting it would
  1438. // mean more complex code if we're to preserve the nice error message.
  1439. // FIXME: Being 100% compliant here would be nice to have.
  1440. // Must preserve cv, as always, unless we're in C-style mode.
  1441. if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
  1442. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1443. return TC_Failed;
  1444. }
  1445. if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
  1446. // This code is analoguous to that in CheckDerivedToBaseConversion, except
  1447. // that it builds the paths in reverse order.
  1448. // To sum up: record all paths to the base and build a nice string from
  1449. // them. Use it to spice up the error message.
  1450. if (!Paths.isRecordingPaths()) {
  1451. Paths.clear();
  1452. Paths.setRecordingPaths(true);
  1453. Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
  1454. }
  1455. std::string PathDisplayStr;
  1456. std::set<unsigned> DisplayedPaths;
  1457. for (clang::CXXBasePath &Path : Paths) {
  1458. if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
  1459. // We haven't displayed a path to this particular base
  1460. // class subobject yet.
  1461. PathDisplayStr += "\n ";
  1462. for (CXXBasePathElement &PE : llvm::reverse(Path))
  1463. PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
  1464. PathDisplayStr += QualType(DestType).getAsString();
  1465. }
  1466. }
  1467. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
  1468. << QualType(SrcType).getUnqualifiedType()
  1469. << QualType(DestType).getUnqualifiedType()
  1470. << PathDisplayStr << OpRange;
  1471. msg = 0;
  1472. return TC_Failed;
  1473. }
  1474. if (Paths.getDetectedVirtual() != nullptr) {
  1475. QualType VirtualBase(Paths.getDetectedVirtual(), 0);
  1476. Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
  1477. << OrigSrcType << OrigDestType << VirtualBase << OpRange;
  1478. msg = 0;
  1479. return TC_Failed;
  1480. }
  1481. if (!CStyle) {
  1482. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1483. SrcType, DestType,
  1484. Paths.front(),
  1485. diag::err_downcast_from_inaccessible_base)) {
  1486. case Sema::AR_accessible:
  1487. case Sema::AR_delayed: // be optimistic
  1488. case Sema::AR_dependent: // be optimistic
  1489. break;
  1490. case Sema::AR_inaccessible:
  1491. msg = 0;
  1492. return TC_Failed;
  1493. }
  1494. }
  1495. Self.BuildBasePathArray(Paths, BasePath);
  1496. Kind = CK_BaseToDerived;
  1497. return TC_Success;
  1498. }
  1499. /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
  1500. /// C++ 5.2.9p9 is valid:
  1501. ///
  1502. /// An rvalue of type "pointer to member of D of type cv1 T" can be
  1503. /// converted to an rvalue of type "pointer to member of B of type cv2 T",
  1504. /// where B is a base class of D [...].
  1505. ///
  1506. TryCastResult
  1507. TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
  1508. QualType DestType, bool CStyle,
  1509. SourceRange OpRange,
  1510. unsigned &msg, CastKind &Kind,
  1511. CXXCastPath &BasePath) {
  1512. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
  1513. if (!DestMemPtr)
  1514. return TC_NotApplicable;
  1515. bool WasOverloadedFunction = false;
  1516. DeclAccessPair FoundOverload;
  1517. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1518. if (FunctionDecl *Fn
  1519. = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
  1520. FoundOverload)) {
  1521. CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
  1522. SrcType = Self.Context.getMemberPointerType(Fn->getType(),
  1523. Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
  1524. WasOverloadedFunction = true;
  1525. }
  1526. }
  1527. const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1528. if (!SrcMemPtr) {
  1529. msg = diag::err_bad_static_cast_member_pointer_nonmp;
  1530. return TC_NotApplicable;
  1531. }
  1532. // Lock down the inheritance model right now in MS ABI, whether or not the
  1533. // pointee types are the same.
  1534. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1535. (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
  1536. (void)Self.isCompleteType(OpRange.getBegin(), DestType);
  1537. }
  1538. // T == T, modulo cv
  1539. if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
  1540. DestMemPtr->getPointeeType()))
  1541. return TC_NotApplicable;
  1542. // B base of D
  1543. QualType SrcClass(SrcMemPtr->getClass(), 0);
  1544. QualType DestClass(DestMemPtr->getClass(), 0);
  1545. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1546. /*DetectVirtual=*/true);
  1547. if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
  1548. return TC_NotApplicable;
  1549. // B is a base of D. But is it an allowed base? If not, it's a hard error.
  1550. if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
  1551. Paths.clear();
  1552. Paths.setRecordingPaths(true);
  1553. bool StillOkay =
  1554. Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
  1555. assert(StillOkay);
  1556. (void)StillOkay;
  1557. std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
  1558. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
  1559. << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
  1560. msg = 0;
  1561. return TC_Failed;
  1562. }
  1563. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  1564. Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
  1565. << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
  1566. msg = 0;
  1567. return TC_Failed;
  1568. }
  1569. if (!CStyle) {
  1570. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1571. DestClass, SrcClass,
  1572. Paths.front(),
  1573. diag::err_upcast_to_inaccessible_base)) {
  1574. case Sema::AR_accessible:
  1575. case Sema::AR_delayed:
  1576. case Sema::AR_dependent:
  1577. // Optimistically assume that the delayed and dependent cases
  1578. // will work out.
  1579. break;
  1580. case Sema::AR_inaccessible:
  1581. msg = 0;
  1582. return TC_Failed;
  1583. }
  1584. }
  1585. if (WasOverloadedFunction) {
  1586. // Resolve the address of the overloaded function again, this time
  1587. // allowing complaints if something goes wrong.
  1588. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  1589. DestType,
  1590. true,
  1591. FoundOverload);
  1592. if (!Fn) {
  1593. msg = 0;
  1594. return TC_Failed;
  1595. }
  1596. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
  1597. if (!SrcExpr.isUsable()) {
  1598. msg = 0;
  1599. return TC_Failed;
  1600. }
  1601. }
  1602. Self.BuildBasePathArray(Paths, BasePath);
  1603. Kind = CK_DerivedToBaseMemberPointer;
  1604. return TC_Success;
  1605. }
  1606. /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
  1607. /// is valid:
  1608. ///
  1609. /// An expression e can be explicitly converted to a type T using a
  1610. /// @c static_cast if the declaration "T t(e);" is well-formed [...].
  1611. TryCastResult
  1612. TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
  1613. Sema::CheckedConversionKind CCK,
  1614. SourceRange OpRange, unsigned &msg,
  1615. CastKind &Kind, bool ListInitialization) {
  1616. if (DestType->isRecordType()) {
  1617. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  1618. diag::err_bad_cast_incomplete) ||
  1619. Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
  1620. diag::err_allocation_of_abstract_type)) {
  1621. msg = 0;
  1622. return TC_Failed;
  1623. }
  1624. }
  1625. InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
  1626. InitializationKind InitKind
  1627. = (CCK == Sema::CCK_CStyleCast)
  1628. ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
  1629. ListInitialization)
  1630. : (CCK == Sema::CCK_FunctionalCast)
  1631. ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
  1632. : InitializationKind::CreateCast(OpRange);
  1633. Expr *SrcExprRaw = SrcExpr.get();
  1634. // FIXME: Per DR242, we should check for an implicit conversion sequence
  1635. // or for a constructor that could be invoked by direct-initialization
  1636. // here, not for an initialization sequence.
  1637. InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
  1638. // At this point of CheckStaticCast, if the destination is a reference,
  1639. // or the expression is an overload expression this has to work.
  1640. // There is no other way that works.
  1641. // On the other hand, if we're checking a C-style cast, we've still got
  1642. // the reinterpret_cast way.
  1643. bool CStyle
  1644. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  1645. if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
  1646. return TC_NotApplicable;
  1647. ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
  1648. if (Result.isInvalid()) {
  1649. msg = 0;
  1650. return TC_Failed;
  1651. }
  1652. if (InitSeq.isConstructorInitialization())
  1653. Kind = CK_ConstructorConversion;
  1654. else
  1655. Kind = CK_NoOp;
  1656. SrcExpr = Result;
  1657. return TC_Success;
  1658. }
  1659. /// TryConstCast - See if a const_cast from source to destination is allowed,
  1660. /// and perform it if it is.
  1661. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  1662. QualType DestType, bool CStyle,
  1663. unsigned &msg) {
  1664. DestType = Self.Context.getCanonicalType(DestType);
  1665. QualType SrcType = SrcExpr.get()->getType();
  1666. bool NeedToMaterializeTemporary = false;
  1667. if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
  1668. // C++11 5.2.11p4:
  1669. // if a pointer to T1 can be explicitly converted to the type "pointer to
  1670. // T2" using a const_cast, then the following conversions can also be
  1671. // made:
  1672. // -- an lvalue of type T1 can be explicitly converted to an lvalue of
  1673. // type T2 using the cast const_cast<T2&>;
  1674. // -- a glvalue of type T1 can be explicitly converted to an xvalue of
  1675. // type T2 using the cast const_cast<T2&&>; and
  1676. // -- if T1 is a class type, a prvalue of type T1 can be explicitly
  1677. // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
  1678. if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
  1679. // Cannot const_cast non-lvalue to lvalue reference type. But if this
  1680. // is C-style, static_cast might find a way, so we simply suggest a
  1681. // message and tell the parent to keep searching.
  1682. msg = diag::err_bad_cxx_cast_rvalue;
  1683. return TC_NotApplicable;
  1684. }
  1685. if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isPRValue()) {
  1686. if (!SrcType->isRecordType()) {
  1687. // Cannot const_cast non-class prvalue to rvalue reference type. But if
  1688. // this is C-style, static_cast can do this.
  1689. msg = diag::err_bad_cxx_cast_rvalue;
  1690. return TC_NotApplicable;
  1691. }
  1692. // Materialize the class prvalue so that the const_cast can bind a
  1693. // reference to it.
  1694. NeedToMaterializeTemporary = true;
  1695. }
  1696. // It's not completely clear under the standard whether we can
  1697. // const_cast bit-field gl-values. Doing so would not be
  1698. // intrinsically complicated, but for now, we say no for
  1699. // consistency with other compilers and await the word of the
  1700. // committee.
  1701. if (SrcExpr.get()->refersToBitField()) {
  1702. msg = diag::err_bad_cxx_cast_bitfield;
  1703. return TC_NotApplicable;
  1704. }
  1705. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1706. SrcType = Self.Context.getPointerType(SrcType);
  1707. }
  1708. // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
  1709. // the rules for const_cast are the same as those used for pointers.
  1710. if (!DestType->isPointerType() &&
  1711. !DestType->isMemberPointerType() &&
  1712. !DestType->isObjCObjectPointerType()) {
  1713. // Cannot cast to non-pointer, non-reference type. Note that, if DestType
  1714. // was a reference type, we converted it to a pointer above.
  1715. // The status of rvalue references isn't entirely clear, but it looks like
  1716. // conversion to them is simply invalid.
  1717. // C++ 5.2.11p3: For two pointer types [...]
  1718. if (!CStyle)
  1719. msg = diag::err_bad_const_cast_dest;
  1720. return TC_NotApplicable;
  1721. }
  1722. if (DestType->isFunctionPointerType() ||
  1723. DestType->isMemberFunctionPointerType()) {
  1724. // Cannot cast direct function pointers.
  1725. // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
  1726. // T is the ultimate pointee of source and target type.
  1727. if (!CStyle)
  1728. msg = diag::err_bad_const_cast_dest;
  1729. return TC_NotApplicable;
  1730. }
  1731. // C++ [expr.const.cast]p3:
  1732. // "For two similar types T1 and T2, [...]"
  1733. //
  1734. // We only allow a const_cast to change cvr-qualifiers, not other kinds of
  1735. // type qualifiers. (Likewise, we ignore other changes when determining
  1736. // whether a cast casts away constness.)
  1737. if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
  1738. return TC_NotApplicable;
  1739. if (NeedToMaterializeTemporary)
  1740. // This is a const_cast from a class prvalue to an rvalue reference type.
  1741. // Materialize a temporary to store the result of the conversion.
  1742. SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
  1743. SrcExpr.get(),
  1744. /*IsLValueReference*/ false);
  1745. return TC_Success;
  1746. }
  1747. // Checks for undefined behavior in reinterpret_cast.
  1748. // The cases that is checked for is:
  1749. // *reinterpret_cast<T*>(&a)
  1750. // reinterpret_cast<T&>(a)
  1751. // where accessing 'a' as type 'T' will result in undefined behavior.
  1752. void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
  1753. bool IsDereference,
  1754. SourceRange Range) {
  1755. unsigned DiagID = IsDereference ?
  1756. diag::warn_pointer_indirection_from_incompatible_type :
  1757. diag::warn_undefined_reinterpret_cast;
  1758. if (Diags.isIgnored(DiagID, Range.getBegin()))
  1759. return;
  1760. QualType SrcTy, DestTy;
  1761. if (IsDereference) {
  1762. if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
  1763. return;
  1764. }
  1765. SrcTy = SrcType->getPointeeType();
  1766. DestTy = DestType->getPointeeType();
  1767. } else {
  1768. if (!DestType->getAs<ReferenceType>()) {
  1769. return;
  1770. }
  1771. SrcTy = SrcType;
  1772. DestTy = DestType->getPointeeType();
  1773. }
  1774. // Cast is compatible if the types are the same.
  1775. if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
  1776. return;
  1777. }
  1778. // or one of the types is a char or void type
  1779. if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
  1780. SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
  1781. return;
  1782. }
  1783. // or one of the types is a tag type.
  1784. if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
  1785. return;
  1786. }
  1787. // FIXME: Scoped enums?
  1788. if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
  1789. (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
  1790. if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
  1791. return;
  1792. }
  1793. }
  1794. Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
  1795. }
  1796. static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
  1797. QualType DestType) {
  1798. QualType SrcType = SrcExpr.get()->getType();
  1799. if (Self.Context.hasSameType(SrcType, DestType))
  1800. return;
  1801. if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
  1802. if (SrcPtrTy->isObjCSelType()) {
  1803. QualType DT = DestType;
  1804. if (isa<PointerType>(DestType))
  1805. DT = DestType->getPointeeType();
  1806. if (!DT.getUnqualifiedType()->isVoidType())
  1807. Self.Diag(SrcExpr.get()->getExprLoc(),
  1808. diag::warn_cast_pointer_from_sel)
  1809. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  1810. }
  1811. }
  1812. /// Diagnose casts that change the calling convention of a pointer to a function
  1813. /// defined in the current TU.
  1814. static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
  1815. QualType DstType, SourceRange OpRange) {
  1816. // Check if this cast would change the calling convention of a function
  1817. // pointer type.
  1818. QualType SrcType = SrcExpr.get()->getType();
  1819. if (Self.Context.hasSameType(SrcType, DstType) ||
  1820. !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
  1821. return;
  1822. const auto *SrcFTy =
  1823. SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
  1824. const auto *DstFTy =
  1825. DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
  1826. CallingConv SrcCC = SrcFTy->getCallConv();
  1827. CallingConv DstCC = DstFTy->getCallConv();
  1828. if (SrcCC == DstCC)
  1829. return;
  1830. // We have a calling convention cast. Check if the source is a pointer to a
  1831. // known, specific function that has already been defined.
  1832. Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
  1833. if (auto *UO = dyn_cast<UnaryOperator>(Src))
  1834. if (UO->getOpcode() == UO_AddrOf)
  1835. Src = UO->getSubExpr()->IgnoreParenImpCasts();
  1836. auto *DRE = dyn_cast<DeclRefExpr>(Src);
  1837. if (!DRE)
  1838. return;
  1839. auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  1840. if (!FD)
  1841. return;
  1842. // Only warn if we are casting from the default convention to a non-default
  1843. // convention. This can happen when the programmer forgot to apply the calling
  1844. // convention to the function declaration and then inserted this cast to
  1845. // satisfy the type system.
  1846. CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
  1847. FD->isVariadic(), FD->isCXXInstanceMember());
  1848. if (DstCC == DefaultCC || SrcCC != DefaultCC)
  1849. return;
  1850. // Diagnose this cast, as it is probably bad.
  1851. StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
  1852. StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
  1853. Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
  1854. << SrcCCName << DstCCName << OpRange;
  1855. // The checks above are cheaper than checking if the diagnostic is enabled.
  1856. // However, it's worth checking if the warning is enabled before we construct
  1857. // a fixit.
  1858. if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
  1859. return;
  1860. // Try to suggest a fixit to change the calling convention of the function
  1861. // whose address was taken. Try to use the latest macro for the convention.
  1862. // For example, users probably want to write "WINAPI" instead of "__stdcall"
  1863. // to match the Windows header declarations.
  1864. SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
  1865. Preprocessor &PP = Self.getPreprocessor();
  1866. SmallVector<TokenValue, 6> AttrTokens;
  1867. SmallString<64> CCAttrText;
  1868. llvm::raw_svector_ostream OS(CCAttrText);
  1869. if (Self.getLangOpts().MicrosoftExt) {
  1870. // __stdcall or __vectorcall
  1871. OS << "__" << DstCCName;
  1872. IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
  1873. AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
  1874. ? TokenValue(II->getTokenID())
  1875. : TokenValue(II));
  1876. } else {
  1877. // __attribute__((stdcall)) or __attribute__((vectorcall))
  1878. OS << "__attribute__((" << DstCCName << "))";
  1879. AttrTokens.push_back(tok::kw___attribute);
  1880. AttrTokens.push_back(tok::l_paren);
  1881. AttrTokens.push_back(tok::l_paren);
  1882. IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
  1883. AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
  1884. ? TokenValue(II->getTokenID())
  1885. : TokenValue(II));
  1886. AttrTokens.push_back(tok::r_paren);
  1887. AttrTokens.push_back(tok::r_paren);
  1888. }
  1889. StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
  1890. if (!AttrSpelling.empty())
  1891. CCAttrText = AttrSpelling;
  1892. OS << ' ';
  1893. Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
  1894. << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
  1895. }
  1896. static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
  1897. const Expr *SrcExpr, QualType DestType,
  1898. Sema &Self) {
  1899. QualType SrcType = SrcExpr->getType();
  1900. // Not warning on reinterpret_cast, boolean, constant expressions, etc
  1901. // are not explicit design choices, but consistent with GCC's behavior.
  1902. // Feel free to modify them if you've reason/evidence for an alternative.
  1903. if (CStyle && SrcType->isIntegralType(Self.Context)
  1904. && !SrcType->isBooleanType()
  1905. && !SrcType->isEnumeralType()
  1906. && !SrcExpr->isIntegerConstantExpr(Self.Context)
  1907. && Self.Context.getTypeSize(DestType) >
  1908. Self.Context.getTypeSize(SrcType)) {
  1909. // Separate between casts to void* and non-void* pointers.
  1910. // Some APIs use (abuse) void* for something like a user context,
  1911. // and often that value is an integer even if it isn't a pointer itself.
  1912. // Having a separate warning flag allows users to control the warning
  1913. // for their workflow.
  1914. unsigned Diag = DestType->isVoidPointerType() ?
  1915. diag::warn_int_to_void_pointer_cast
  1916. : diag::warn_int_to_pointer_cast;
  1917. Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
  1918. }
  1919. }
  1920. static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
  1921. ExprResult &Result) {
  1922. // We can only fix an overloaded reinterpret_cast if
  1923. // - it is a template with explicit arguments that resolves to an lvalue
  1924. // unambiguously, or
  1925. // - it is the only function in an overload set that may have its address
  1926. // taken.
  1927. Expr *E = Result.get();
  1928. // TODO: what if this fails because of DiagnoseUseOfDecl or something
  1929. // like it?
  1930. if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  1931. Result,
  1932. Expr::getValueKindForType(DestType) ==
  1933. VK_PRValue // Convert Fun to Ptr
  1934. ) &&
  1935. Result.isUsable())
  1936. return true;
  1937. // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
  1938. // preserves Result.
  1939. Result = E;
  1940. if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
  1941. Result, /*DoFunctionPointerConversion=*/true))
  1942. return false;
  1943. return Result.isUsable();
  1944. }
  1945. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  1946. QualType DestType, bool CStyle,
  1947. SourceRange OpRange,
  1948. unsigned &msg,
  1949. CastKind &Kind) {
  1950. bool IsLValueCast = false;
  1951. DestType = Self.Context.getCanonicalType(DestType);
  1952. QualType SrcType = SrcExpr.get()->getType();
  1953. // Is the source an overloaded name? (i.e. &foo)
  1954. // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
  1955. if (SrcType == Self.Context.OverloadTy) {
  1956. ExprResult FixedExpr = SrcExpr;
  1957. if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
  1958. return TC_NotApplicable;
  1959. assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
  1960. SrcExpr = FixedExpr;
  1961. SrcType = SrcExpr.get()->getType();
  1962. }
  1963. if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
  1964. if (!SrcExpr.get()->isGLValue()) {
  1965. // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
  1966. // similar comment in const_cast.
  1967. msg = diag::err_bad_cxx_cast_rvalue;
  1968. return TC_NotApplicable;
  1969. }
  1970. if (!CStyle) {
  1971. Self.CheckCompatibleReinterpretCast(SrcType, DestType,
  1972. /*IsDereference=*/false, OpRange);
  1973. }
  1974. // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
  1975. // same effect as the conversion *reinterpret_cast<T*>(&x) with the
  1976. // built-in & and * operators.
  1977. const char *inappropriate = nullptr;
  1978. switch (SrcExpr.get()->getObjectKind()) {
  1979. case OK_Ordinary:
  1980. break;
  1981. case OK_BitField:
  1982. msg = diag::err_bad_cxx_cast_bitfield;
  1983. return TC_NotApplicable;
  1984. // FIXME: Use a specific diagnostic for the rest of these cases.
  1985. case OK_VectorComponent: inappropriate = "vector element"; break;
  1986. case OK_MatrixComponent:
  1987. inappropriate = "matrix element";
  1988. break;
  1989. case OK_ObjCProperty: inappropriate = "property expression"; break;
  1990. case OK_ObjCSubscript: inappropriate = "container subscripting expression";
  1991. break;
  1992. }
  1993. if (inappropriate) {
  1994. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
  1995. << inappropriate << DestType
  1996. << OpRange << SrcExpr.get()->getSourceRange();
  1997. msg = 0; SrcExpr = ExprError();
  1998. return TC_NotApplicable;
  1999. }
  2000. // This code does this transformation for the checked types.
  2001. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  2002. SrcType = Self.Context.getPointerType(SrcType);
  2003. IsLValueCast = true;
  2004. }
  2005. // Canonicalize source for comparison.
  2006. SrcType = Self.Context.getCanonicalType(SrcType);
  2007. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
  2008. *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  2009. if (DestMemPtr && SrcMemPtr) {
  2010. // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
  2011. // can be explicitly converted to an rvalue of type "pointer to member
  2012. // of Y of type T2" if T1 and T2 are both function types or both object
  2013. // types.
  2014. if (DestMemPtr->isMemberFunctionPointer() !=
  2015. SrcMemPtr->isMemberFunctionPointer())
  2016. return TC_NotApplicable;
  2017. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2018. // We need to determine the inheritance model that the class will use if
  2019. // haven't yet.
  2020. (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
  2021. (void)Self.isCompleteType(OpRange.getBegin(), DestType);
  2022. }
  2023. // Don't allow casting between member pointers of different sizes.
  2024. if (Self.Context.getTypeSize(DestMemPtr) !=
  2025. Self.Context.getTypeSize(SrcMemPtr)) {
  2026. msg = diag::err_bad_cxx_cast_member_pointer_size;
  2027. return TC_Failed;
  2028. }
  2029. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
  2030. // constness.
  2031. // A reinterpret_cast followed by a const_cast can, though, so in C-style,
  2032. // we accept it.
  2033. if (auto CACK =
  2034. CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  2035. /*CheckObjCLifetime=*/CStyle))
  2036. return getCastAwayConstnessCastKind(CACK, msg);
  2037. // A valid member pointer cast.
  2038. assert(!IsLValueCast);
  2039. Kind = CK_ReinterpretMemberPointer;
  2040. return TC_Success;
  2041. }
  2042. // See below for the enumeral issue.
  2043. if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
  2044. // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
  2045. // type large enough to hold it. A value of std::nullptr_t can be
  2046. // converted to an integral type; the conversion has the same meaning
  2047. // and validity as a conversion of (void*)0 to the integral type.
  2048. if (Self.Context.getTypeSize(SrcType) >
  2049. Self.Context.getTypeSize(DestType)) {
  2050. msg = diag::err_bad_reinterpret_cast_small_int;
  2051. return TC_Failed;
  2052. }
  2053. Kind = CK_PointerToIntegral;
  2054. return TC_Success;
  2055. }
  2056. // Allow reinterpret_casts between vectors of the same size and
  2057. // between vectors and integers of the same size.
  2058. bool destIsVector = DestType->isVectorType();
  2059. bool srcIsVector = SrcType->isVectorType();
  2060. if (srcIsVector || destIsVector) {
  2061. // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
  2062. if (Self.isValidSveBitcast(SrcType, DestType)) {
  2063. Kind = CK_BitCast;
  2064. return TC_Success;
  2065. }
  2066. // The non-vector type, if any, must have integral type. This is
  2067. // the same rule that C vector casts use; note, however, that enum
  2068. // types are not integral in C++.
  2069. if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
  2070. (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
  2071. return TC_NotApplicable;
  2072. // The size we want to consider is eltCount * eltSize.
  2073. // That's exactly what the lax-conversion rules will check.
  2074. if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
  2075. Kind = CK_BitCast;
  2076. return TC_Success;
  2077. }
  2078. if (Self.LangOpts.OpenCL && !CStyle) {
  2079. if (DestType->isExtVectorType() || SrcType->isExtVectorType()) {
  2080. // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
  2081. if (Self.areVectorTypesSameSize(SrcType, DestType)) {
  2082. Kind = CK_BitCast;
  2083. return TC_Success;
  2084. }
  2085. }
  2086. }
  2087. // Otherwise, pick a reasonable diagnostic.
  2088. if (!destIsVector)
  2089. msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
  2090. else if (!srcIsVector)
  2091. msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
  2092. else
  2093. msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
  2094. return TC_Failed;
  2095. }
  2096. if (SrcType == DestType) {
  2097. // C++ 5.2.10p2 has a note that mentions that, subject to all other
  2098. // restrictions, a cast to the same type is allowed so long as it does not
  2099. // cast away constness. In C++98, the intent was not entirely clear here,
  2100. // since all other paragraphs explicitly forbid casts to the same type.
  2101. // C++11 clarifies this case with p2.
  2102. //
  2103. // The only allowed types are: integral, enumeration, pointer, or
  2104. // pointer-to-member types. We also won't restrict Obj-C pointers either.
  2105. Kind = CK_NoOp;
  2106. TryCastResult Result = TC_NotApplicable;
  2107. if (SrcType->isIntegralOrEnumerationType() ||
  2108. SrcType->isAnyPointerType() ||
  2109. SrcType->isMemberPointerType() ||
  2110. SrcType->isBlockPointerType()) {
  2111. Result = TC_Success;
  2112. }
  2113. return Result;
  2114. }
  2115. bool destIsPtr = DestType->isAnyPointerType() ||
  2116. DestType->isBlockPointerType();
  2117. bool srcIsPtr = SrcType->isAnyPointerType() ||
  2118. SrcType->isBlockPointerType();
  2119. if (!destIsPtr && !srcIsPtr) {
  2120. // Except for std::nullptr_t->integer and lvalue->reference, which are
  2121. // handled above, at least one of the two arguments must be a pointer.
  2122. return TC_NotApplicable;
  2123. }
  2124. if (DestType->isIntegralType(Self.Context)) {
  2125. assert(srcIsPtr && "One type must be a pointer");
  2126. // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
  2127. // type large enough to hold it; except in Microsoft mode, where the
  2128. // integral type size doesn't matter (except we don't allow bool).
  2129. if ((Self.Context.getTypeSize(SrcType) >
  2130. Self.Context.getTypeSize(DestType))) {
  2131. bool MicrosoftException =
  2132. Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
  2133. if (MicrosoftException) {
  2134. unsigned Diag = SrcType->isVoidPointerType()
  2135. ? diag::warn_void_pointer_to_int_cast
  2136. : diag::warn_pointer_to_int_cast;
  2137. Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
  2138. } else {
  2139. msg = diag::err_bad_reinterpret_cast_small_int;
  2140. return TC_Failed;
  2141. }
  2142. }
  2143. Kind = CK_PointerToIntegral;
  2144. return TC_Success;
  2145. }
  2146. if (SrcType->isIntegralOrEnumerationType()) {
  2147. assert(destIsPtr && "One type must be a pointer");
  2148. checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
  2149. // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
  2150. // converted to a pointer.
  2151. // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
  2152. // necessarily converted to a null pointer value.]
  2153. Kind = CK_IntegralToPointer;
  2154. return TC_Success;
  2155. }
  2156. if (!destIsPtr || !srcIsPtr) {
  2157. // With the valid non-pointer conversions out of the way, we can be even
  2158. // more stringent.
  2159. return TC_NotApplicable;
  2160. }
  2161. // Cannot convert between block pointers and Objective-C object pointers.
  2162. if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
  2163. (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
  2164. return TC_NotApplicable;
  2165. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
  2166. // The C-style cast operator can.
  2167. TryCastResult SuccessResult = TC_Success;
  2168. if (auto CACK =
  2169. CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  2170. /*CheckObjCLifetime=*/CStyle))
  2171. SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
  2172. if (IsAddressSpaceConversion(SrcType, DestType)) {
  2173. Kind = CK_AddressSpaceConversion;
  2174. assert(SrcType->isPointerType() && DestType->isPointerType());
  2175. if (!CStyle &&
  2176. !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
  2177. SrcType->getPointeeType().getQualifiers())) {
  2178. SuccessResult = TC_Failed;
  2179. }
  2180. } else if (IsLValueCast) {
  2181. Kind = CK_LValueBitCast;
  2182. } else if (DestType->isObjCObjectPointerType()) {
  2183. Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
  2184. } else if (DestType->isBlockPointerType()) {
  2185. if (!SrcType->isBlockPointerType()) {
  2186. Kind = CK_AnyPointerToBlockPointerCast;
  2187. } else {
  2188. Kind = CK_BitCast;
  2189. }
  2190. } else {
  2191. Kind = CK_BitCast;
  2192. }
  2193. // Any pointer can be cast to an Objective-C pointer type with a C-style
  2194. // cast.
  2195. if (CStyle && DestType->isObjCObjectPointerType()) {
  2196. return SuccessResult;
  2197. }
  2198. if (CStyle)
  2199. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  2200. DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
  2201. // Not casting away constness, so the only remaining check is for compatible
  2202. // pointer categories.
  2203. if (SrcType->isFunctionPointerType()) {
  2204. if (DestType->isFunctionPointerType()) {
  2205. // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
  2206. // a pointer to a function of a different type.
  2207. return SuccessResult;
  2208. }
  2209. // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
  2210. // an object type or vice versa is conditionally-supported.
  2211. // Compilers support it in C++03 too, though, because it's necessary for
  2212. // casting the return value of dlsym() and GetProcAddress().
  2213. // FIXME: Conditionally-supported behavior should be configurable in the
  2214. // TargetInfo or similar.
  2215. Self.Diag(OpRange.getBegin(),
  2216. Self.getLangOpts().CPlusPlus11 ?
  2217. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  2218. << OpRange;
  2219. return SuccessResult;
  2220. }
  2221. if (DestType->isFunctionPointerType()) {
  2222. // See above.
  2223. Self.Diag(OpRange.getBegin(),
  2224. Self.getLangOpts().CPlusPlus11 ?
  2225. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  2226. << OpRange;
  2227. return SuccessResult;
  2228. }
  2229. // Diagnose address space conversion in nested pointers.
  2230. QualType DestPtee = DestType->getPointeeType().isNull()
  2231. ? DestType->getPointeeType()
  2232. : DestType->getPointeeType()->getPointeeType();
  2233. QualType SrcPtee = SrcType->getPointeeType().isNull()
  2234. ? SrcType->getPointeeType()
  2235. : SrcType->getPointeeType()->getPointeeType();
  2236. while (!DestPtee.isNull() && !SrcPtee.isNull()) {
  2237. if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
  2238. Self.Diag(OpRange.getBegin(),
  2239. diag::warn_bad_cxx_cast_nested_pointer_addr_space)
  2240. << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2241. break;
  2242. }
  2243. DestPtee = DestPtee->getPointeeType();
  2244. SrcPtee = SrcPtee->getPointeeType();
  2245. }
  2246. // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
  2247. // a pointer to an object of different type.
  2248. // Void pointers are not specified, but supported by every compiler out there.
  2249. // So we finish by allowing everything that remains - it's got to be two
  2250. // object pointers.
  2251. return SuccessResult;
  2252. }
  2253. static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
  2254. QualType DestType, bool CStyle,
  2255. unsigned &msg, CastKind &Kind) {
  2256. if (!Self.getLangOpts().OpenCL)
  2257. // FIXME: As compiler doesn't have any information about overlapping addr
  2258. // spaces at the moment we have to be permissive here.
  2259. return TC_NotApplicable;
  2260. // Even though the logic below is general enough and can be applied to
  2261. // non-OpenCL mode too, we fast-path above because no other languages
  2262. // define overlapping address spaces currently.
  2263. auto SrcType = SrcExpr.get()->getType();
  2264. // FIXME: Should this be generalized to references? The reference parameter
  2265. // however becomes a reference pointee type here and therefore rejected.
  2266. // Perhaps this is the right behavior though according to C++.
  2267. auto SrcPtrType = SrcType->getAs<PointerType>();
  2268. if (!SrcPtrType)
  2269. return TC_NotApplicable;
  2270. auto DestPtrType = DestType->getAs<PointerType>();
  2271. if (!DestPtrType)
  2272. return TC_NotApplicable;
  2273. auto SrcPointeeType = SrcPtrType->getPointeeType();
  2274. auto DestPointeeType = DestPtrType->getPointeeType();
  2275. if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
  2276. msg = diag::err_bad_cxx_cast_addr_space_mismatch;
  2277. return TC_Failed;
  2278. }
  2279. auto SrcPointeeTypeWithoutAS =
  2280. Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
  2281. auto DestPointeeTypeWithoutAS =
  2282. Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
  2283. if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
  2284. DestPointeeTypeWithoutAS)) {
  2285. Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
  2286. ? CK_NoOp
  2287. : CK_AddressSpaceConversion;
  2288. return TC_Success;
  2289. } else {
  2290. return TC_NotApplicable;
  2291. }
  2292. }
  2293. void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
  2294. // In OpenCL only conversions between pointers to objects in overlapping
  2295. // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
  2296. // with any named one, except for constant.
  2297. // Converting the top level pointee addrspace is permitted for compatible
  2298. // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
  2299. // if any of the nested pointee addrspaces differ, we emit a warning
  2300. // regardless of addrspace compatibility. This makes
  2301. // local int ** p;
  2302. // return (generic int **) p;
  2303. // warn even though local -> generic is permitted.
  2304. if (Self.getLangOpts().OpenCL) {
  2305. const Type *DestPtr, *SrcPtr;
  2306. bool Nested = false;
  2307. unsigned DiagID = diag::err_typecheck_incompatible_address_space;
  2308. DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
  2309. SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
  2310. while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
  2311. const PointerType *DestPPtr = cast<PointerType>(DestPtr);
  2312. const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
  2313. QualType DestPPointee = DestPPtr->getPointeeType();
  2314. QualType SrcPPointee = SrcPPtr->getPointeeType();
  2315. if (Nested
  2316. ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
  2317. : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
  2318. Self.Diag(OpRange.getBegin(), DiagID)
  2319. << SrcType << DestType << Sema::AA_Casting
  2320. << SrcExpr.get()->getSourceRange();
  2321. if (!Nested)
  2322. SrcExpr = ExprError();
  2323. return;
  2324. }
  2325. DestPtr = DestPPtr->getPointeeType().getTypePtr();
  2326. SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
  2327. Nested = true;
  2328. DiagID = diag::ext_nested_pointer_qualifier_mismatch;
  2329. }
  2330. }
  2331. }
  2332. bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) {
  2333. bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() ==
  2334. LangOptions::AltivecSrcCompatKind::XL;
  2335. VectorType::VectorKind VKind = VecTy->getVectorKind();
  2336. if ((VKind == VectorType::AltiVecVector) ||
  2337. (SrcCompatXL && ((VKind == VectorType::AltiVecBool) ||
  2338. (VKind == VectorType::AltiVecPixel)))) {
  2339. return true;
  2340. }
  2341. return false;
  2342. }
  2343. bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
  2344. QualType SrcTy) {
  2345. bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() ==
  2346. LangOptions::AltivecSrcCompatKind::GCC;
  2347. if (this->getLangOpts().AltiVec && SrcCompatGCC) {
  2348. this->Diag(R.getBegin(),
  2349. diag::err_invalid_conversion_between_vector_and_integer)
  2350. << VecTy << SrcTy << R;
  2351. return true;
  2352. }
  2353. return false;
  2354. }
  2355. void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
  2356. bool ListInitialization) {
  2357. assert(Self.getLangOpts().CPlusPlus);
  2358. // Handle placeholders.
  2359. if (isPlaceholder()) {
  2360. // C-style casts can resolve __unknown_any types.
  2361. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  2362. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  2363. SrcExpr.get(), Kind,
  2364. ValueKind, BasePath);
  2365. return;
  2366. }
  2367. checkNonOverloadPlaceholders();
  2368. if (SrcExpr.isInvalid())
  2369. return;
  2370. }
  2371. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  2372. // This test is outside everything else because it's the only case where
  2373. // a non-lvalue-reference target type does not lead to decay.
  2374. if (DestType->isVoidType()) {
  2375. Kind = CK_ToVoid;
  2376. if (claimPlaceholder(BuiltinType::Overload)) {
  2377. Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  2378. SrcExpr, /* Decay Function to ptr */ false,
  2379. /* Complain */ true, DestRange, DestType,
  2380. diag::err_bad_cstyle_cast_overload);
  2381. if (SrcExpr.isInvalid())
  2382. return;
  2383. }
  2384. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2385. return;
  2386. }
  2387. // If the type is dependent, we won't do any other semantic analysis now.
  2388. if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
  2389. SrcExpr.get()->isValueDependent()) {
  2390. assert(Kind == CK_Dependent);
  2391. return;
  2392. }
  2393. if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
  2394. !isPlaceholder(BuiltinType::Overload)) {
  2395. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2396. if (SrcExpr.isInvalid())
  2397. return;
  2398. }
  2399. // AltiVec vector initialization with a single literal.
  2400. if (const VectorType *vecTy = DestType->getAs<VectorType>()) {
  2401. if (Self.CheckAltivecInitFromScalar(OpRange, DestType,
  2402. SrcExpr.get()->getType())) {
  2403. SrcExpr = ExprError();
  2404. return;
  2405. }
  2406. if (Self.ShouldSplatAltivecScalarInCast(vecTy) &&
  2407. (SrcExpr.get()->getType()->isIntegerType() ||
  2408. SrcExpr.get()->getType()->isFloatingType())) {
  2409. Kind = CK_VectorSplat;
  2410. SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
  2411. return;
  2412. }
  2413. }
  2414. // C++ [expr.cast]p5: The conversions performed by
  2415. // - a const_cast,
  2416. // - a static_cast,
  2417. // - a static_cast followed by a const_cast,
  2418. // - a reinterpret_cast, or
  2419. // - a reinterpret_cast followed by a const_cast,
  2420. // can be performed using the cast notation of explicit type conversion.
  2421. // [...] If a conversion can be interpreted in more than one of the ways
  2422. // listed above, the interpretation that appears first in the list is used,
  2423. // even if a cast resulting from that interpretation is ill-formed.
  2424. // In plain language, this means trying a const_cast ...
  2425. // Note that for address space we check compatibility after const_cast.
  2426. unsigned msg = diag::err_bad_cxx_cast_generic;
  2427. TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
  2428. /*CStyle*/ true, msg);
  2429. if (SrcExpr.isInvalid())
  2430. return;
  2431. if (isValidCast(tcr))
  2432. Kind = CK_NoOp;
  2433. Sema::CheckedConversionKind CCK =
  2434. FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
  2435. if (tcr == TC_NotApplicable) {
  2436. tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
  2437. Kind);
  2438. if (SrcExpr.isInvalid())
  2439. return;
  2440. if (tcr == TC_NotApplicable) {
  2441. // ... or if that is not possible, a static_cast, ignoring const and
  2442. // addr space, ...
  2443. tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
  2444. BasePath, ListInitialization);
  2445. if (SrcExpr.isInvalid())
  2446. return;
  2447. if (tcr == TC_NotApplicable) {
  2448. // ... and finally a reinterpret_cast, ignoring const and addr space.
  2449. tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
  2450. OpRange, msg, Kind);
  2451. if (SrcExpr.isInvalid())
  2452. return;
  2453. }
  2454. }
  2455. }
  2456. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  2457. isValidCast(tcr))
  2458. checkObjCConversion(CCK);
  2459. if (tcr != TC_Success && msg != 0) {
  2460. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  2461. DeclAccessPair Found;
  2462. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  2463. DestType,
  2464. /*Complain*/ true,
  2465. Found);
  2466. if (Fn) {
  2467. // If DestType is a function type (not to be confused with the function
  2468. // pointer type), it will be possible to resolve the function address,
  2469. // but the type cast should be considered as failure.
  2470. OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
  2471. Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
  2472. << OE->getName() << DestType << OpRange
  2473. << OE->getQualifierLoc().getSourceRange();
  2474. Self.NoteAllOverloadCandidates(SrcExpr.get());
  2475. }
  2476. } else {
  2477. diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
  2478. OpRange, SrcExpr.get(), DestType, ListInitialization);
  2479. }
  2480. }
  2481. if (isValidCast(tcr)) {
  2482. if (Kind == CK_BitCast)
  2483. checkCastAlign();
  2484. if (!checkCastFunctionType(Self, SrcExpr, DestType))
  2485. Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
  2486. << SrcExpr.get()->getType() << DestType << OpRange;
  2487. } else {
  2488. SrcExpr = ExprError();
  2489. }
  2490. }
  2491. /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
  2492. /// non-matching type. Such as enum function call to int, int call to
  2493. /// pointer; etc. Cast to 'void' is an exception.
  2494. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
  2495. QualType DestType) {
  2496. if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
  2497. SrcExpr.get()->getExprLoc()))
  2498. return;
  2499. if (!isa<CallExpr>(SrcExpr.get()))
  2500. return;
  2501. QualType SrcType = SrcExpr.get()->getType();
  2502. if (DestType.getUnqualifiedType()->isVoidType())
  2503. return;
  2504. if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
  2505. && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
  2506. return;
  2507. if (SrcType->isIntegerType() && DestType->isIntegerType() &&
  2508. (SrcType->isBooleanType() == DestType->isBooleanType()) &&
  2509. (SrcType->isEnumeralType() == DestType->isEnumeralType()))
  2510. return;
  2511. if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
  2512. return;
  2513. if (SrcType->isEnumeralType() && DestType->isEnumeralType())
  2514. return;
  2515. if (SrcType->isComplexType() && DestType->isComplexType())
  2516. return;
  2517. if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
  2518. return;
  2519. if (SrcType->isFixedPointType() && DestType->isFixedPointType())
  2520. return;
  2521. Self.Diag(SrcExpr.get()->getExprLoc(),
  2522. diag::warn_bad_function_cast)
  2523. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2524. }
  2525. /// Check the semantics of a C-style cast operation, in C.
  2526. void CastOperation::CheckCStyleCast() {
  2527. assert(!Self.getLangOpts().CPlusPlus);
  2528. // C-style casts can resolve __unknown_any types.
  2529. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  2530. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  2531. SrcExpr.get(), Kind,
  2532. ValueKind, BasePath);
  2533. return;
  2534. }
  2535. // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
  2536. // type needs to be scalar.
  2537. if (DestType->isVoidType()) {
  2538. // We don't necessarily do lvalue-to-rvalue conversions on this.
  2539. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2540. if (SrcExpr.isInvalid())
  2541. return;
  2542. // Cast to void allows any expr type.
  2543. Kind = CK_ToVoid;
  2544. return;
  2545. }
  2546. // If the type is dependent, we won't do any other semantic analysis now.
  2547. if (Self.getASTContext().isDependenceAllowed() &&
  2548. (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
  2549. SrcExpr.get()->isValueDependent())) {
  2550. assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||
  2551. SrcExpr.get()->containsErrors()) &&
  2552. "should only occur in error-recovery path.");
  2553. assert(Kind == CK_Dependent);
  2554. return;
  2555. }
  2556. // Overloads are allowed with C extensions, so we need to support them.
  2557. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  2558. DeclAccessPair DAP;
  2559. if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
  2560. SrcExpr.get(), DestType, /*Complain=*/true, DAP))
  2561. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
  2562. else
  2563. return;
  2564. assert(SrcExpr.isUsable());
  2565. }
  2566. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2567. if (SrcExpr.isInvalid())
  2568. return;
  2569. QualType SrcType = SrcExpr.get()->getType();
  2570. assert(!SrcType->isPlaceholderType());
  2571. checkAddressSpaceCast(SrcType, DestType);
  2572. if (SrcExpr.isInvalid())
  2573. return;
  2574. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  2575. diag::err_typecheck_cast_to_incomplete)) {
  2576. SrcExpr = ExprError();
  2577. return;
  2578. }
  2579. // Allow casting a sizeless built-in type to itself.
  2580. if (DestType->isSizelessBuiltinType() &&
  2581. Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
  2582. Kind = CK_NoOp;
  2583. return;
  2584. }
  2585. // Allow bitcasting between compatible SVE vector types.
  2586. if ((SrcType->isVectorType() || DestType->isVectorType()) &&
  2587. Self.isValidSveBitcast(SrcType, DestType)) {
  2588. Kind = CK_BitCast;
  2589. return;
  2590. }
  2591. if (!DestType->isScalarType() && !DestType->isVectorType() &&
  2592. !DestType->isMatrixType()) {
  2593. const RecordType *DestRecordTy = DestType->getAs<RecordType>();
  2594. if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
  2595. // GCC struct/union extension: allow cast to self.
  2596. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
  2597. << DestType << SrcExpr.get()->getSourceRange();
  2598. Kind = CK_NoOp;
  2599. return;
  2600. }
  2601. // GCC's cast to union extension.
  2602. if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
  2603. RecordDecl *RD = DestRecordTy->getDecl();
  2604. if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
  2605. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
  2606. << SrcExpr.get()->getSourceRange();
  2607. Kind = CK_ToUnion;
  2608. return;
  2609. } else {
  2610. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
  2611. << SrcType << SrcExpr.get()->getSourceRange();
  2612. SrcExpr = ExprError();
  2613. return;
  2614. }
  2615. }
  2616. // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
  2617. if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
  2618. Expr::EvalResult Result;
  2619. if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
  2620. llvm::APSInt CastInt = Result.Val.getInt();
  2621. if (0 == CastInt) {
  2622. Kind = CK_ZeroToOCLOpaqueType;
  2623. return;
  2624. }
  2625. Self.Diag(OpRange.getBegin(),
  2626. diag::err_opencl_cast_non_zero_to_event_t)
  2627. << toString(CastInt, 10) << SrcExpr.get()->getSourceRange();
  2628. SrcExpr = ExprError();
  2629. return;
  2630. }
  2631. }
  2632. // Reject any other conversions to non-scalar types.
  2633. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
  2634. << DestType << SrcExpr.get()->getSourceRange();
  2635. SrcExpr = ExprError();
  2636. return;
  2637. }
  2638. // The type we're casting to is known to be a scalar, a vector, or a matrix.
  2639. // Require the operand to be a scalar, a vector, or a matrix.
  2640. if (!SrcType->isScalarType() && !SrcType->isVectorType() &&
  2641. !SrcType->isMatrixType()) {
  2642. Self.Diag(SrcExpr.get()->getExprLoc(),
  2643. diag::err_typecheck_expect_scalar_operand)
  2644. << SrcType << SrcExpr.get()->getSourceRange();
  2645. SrcExpr = ExprError();
  2646. return;
  2647. }
  2648. if (DestType->isExtVectorType()) {
  2649. SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
  2650. return;
  2651. }
  2652. if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) {
  2653. if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind))
  2654. SrcExpr = ExprError();
  2655. return;
  2656. }
  2657. if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
  2658. if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) {
  2659. SrcExpr = ExprError();
  2660. return;
  2661. }
  2662. if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) &&
  2663. (SrcType->isIntegerType() || SrcType->isFloatingType())) {
  2664. Kind = CK_VectorSplat;
  2665. SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
  2666. } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
  2667. SrcExpr = ExprError();
  2668. }
  2669. return;
  2670. }
  2671. if (SrcType->isVectorType()) {
  2672. if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
  2673. SrcExpr = ExprError();
  2674. return;
  2675. }
  2676. // The source and target types are both scalars, i.e.
  2677. // - arithmetic types (fundamental, enum, and complex)
  2678. // - all kinds of pointers
  2679. // Note that member pointers were filtered out with C++, above.
  2680. if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
  2681. Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
  2682. SrcExpr = ExprError();
  2683. return;
  2684. }
  2685. // Can't cast to or from bfloat
  2686. if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) {
  2687. Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16)
  2688. << SrcExpr.get()->getSourceRange();
  2689. SrcExpr = ExprError();
  2690. return;
  2691. }
  2692. if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) {
  2693. Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16)
  2694. << SrcExpr.get()->getSourceRange();
  2695. SrcExpr = ExprError();
  2696. return;
  2697. }
  2698. // If either type is a pointer, the other type has to be either an
  2699. // integer or a pointer.
  2700. if (!DestType->isArithmeticType()) {
  2701. if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
  2702. Self.Diag(SrcExpr.get()->getExprLoc(),
  2703. diag::err_cast_pointer_from_non_pointer_int)
  2704. << SrcType << SrcExpr.get()->getSourceRange();
  2705. SrcExpr = ExprError();
  2706. return;
  2707. }
  2708. checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
  2709. Self);
  2710. } else if (!SrcType->isArithmeticType()) {
  2711. if (!DestType->isIntegralType(Self.Context) &&
  2712. DestType->isArithmeticType()) {
  2713. Self.Diag(SrcExpr.get()->getBeginLoc(),
  2714. diag::err_cast_pointer_to_non_pointer_int)
  2715. << DestType << SrcExpr.get()->getSourceRange();
  2716. SrcExpr = ExprError();
  2717. return;
  2718. }
  2719. if ((Self.Context.getTypeSize(SrcType) >
  2720. Self.Context.getTypeSize(DestType)) &&
  2721. !DestType->isBooleanType()) {
  2722. // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
  2723. // Except as previously specified, the result is implementation-defined.
  2724. // If the result cannot be represented in the integer type, the behavior
  2725. // is undefined. The result need not be in the range of values of any
  2726. // integer type.
  2727. unsigned Diag;
  2728. if (SrcType->isVoidPointerType())
  2729. Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
  2730. : diag::warn_void_pointer_to_int_cast;
  2731. else if (DestType->isEnumeralType())
  2732. Diag = diag::warn_pointer_to_enum_cast;
  2733. else
  2734. Diag = diag::warn_pointer_to_int_cast;
  2735. Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
  2736. }
  2737. }
  2738. if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(
  2739. "cl_khr_fp16", Self.getLangOpts())) {
  2740. if (DestType->isHalfType()) {
  2741. Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
  2742. << DestType << SrcExpr.get()->getSourceRange();
  2743. SrcExpr = ExprError();
  2744. return;
  2745. }
  2746. }
  2747. // ARC imposes extra restrictions on casts.
  2748. if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
  2749. checkObjCConversion(Sema::CCK_CStyleCast);
  2750. if (SrcExpr.isInvalid())
  2751. return;
  2752. const PointerType *CastPtr = DestType->getAs<PointerType>();
  2753. if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
  2754. if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
  2755. Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
  2756. Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
  2757. if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
  2758. ExprPtr->getPointeeType()->isObjCLifetimeType() &&
  2759. !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
  2760. Self.Diag(SrcExpr.get()->getBeginLoc(),
  2761. diag::err_typecheck_incompatible_ownership)
  2762. << SrcType << DestType << Sema::AA_Casting
  2763. << SrcExpr.get()->getSourceRange();
  2764. return;
  2765. }
  2766. }
  2767. }
  2768. else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
  2769. Self.Diag(SrcExpr.get()->getBeginLoc(),
  2770. diag::err_arc_convesion_of_weak_unavailable)
  2771. << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2772. SrcExpr = ExprError();
  2773. return;
  2774. }
  2775. }
  2776. if (!checkCastFunctionType(Self, SrcExpr, DestType))
  2777. Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
  2778. << SrcType << DestType << OpRange;
  2779. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  2780. DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
  2781. DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
  2782. Kind = Self.PrepareScalarCast(SrcExpr, DestType);
  2783. if (SrcExpr.isInvalid())
  2784. return;
  2785. if (Kind == CK_BitCast)
  2786. checkCastAlign();
  2787. }
  2788. void CastOperation::CheckBuiltinBitCast() {
  2789. QualType SrcType = SrcExpr.get()->getType();
  2790. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  2791. diag::err_typecheck_cast_to_incomplete) ||
  2792. Self.RequireCompleteType(OpRange.getBegin(), SrcType,
  2793. diag::err_incomplete_type)) {
  2794. SrcExpr = ExprError();
  2795. return;
  2796. }
  2797. if (SrcExpr.get()->isPRValue())
  2798. SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
  2799. /*IsLValueReference=*/false);
  2800. CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
  2801. CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
  2802. if (DestSize != SourceSize) {
  2803. Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
  2804. << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
  2805. SrcExpr = ExprError();
  2806. return;
  2807. }
  2808. if (!DestType.isTriviallyCopyableType(Self.Context)) {
  2809. Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
  2810. << 1;
  2811. SrcExpr = ExprError();
  2812. return;
  2813. }
  2814. if (!SrcType.isTriviallyCopyableType(Self.Context)) {
  2815. Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
  2816. << 0;
  2817. SrcExpr = ExprError();
  2818. return;
  2819. }
  2820. Kind = CK_LValueToRValueBitCast;
  2821. }
  2822. /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
  2823. /// const, volatile or both.
  2824. static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
  2825. QualType DestType) {
  2826. if (SrcExpr.isInvalid())
  2827. return;
  2828. QualType SrcType = SrcExpr.get()->getType();
  2829. if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
  2830. DestType->isLValueReferenceType()))
  2831. return;
  2832. QualType TheOffendingSrcType, TheOffendingDestType;
  2833. Qualifiers CastAwayQualifiers;
  2834. if (CastsAwayConstness(Self, SrcType, DestType, true, false,
  2835. &TheOffendingSrcType, &TheOffendingDestType,
  2836. &CastAwayQualifiers) !=
  2837. CastAwayConstnessKind::CACK_Similar)
  2838. return;
  2839. // FIXME: 'restrict' is not properly handled here.
  2840. int qualifiers = -1;
  2841. if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
  2842. qualifiers = 0;
  2843. } else if (CastAwayQualifiers.hasConst()) {
  2844. qualifiers = 1;
  2845. } else if (CastAwayQualifiers.hasVolatile()) {
  2846. qualifiers = 2;
  2847. }
  2848. // This is a variant of int **x; const int **y = (const int **)x;
  2849. if (qualifiers == -1)
  2850. Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
  2851. << SrcType << DestType;
  2852. else
  2853. Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
  2854. << TheOffendingSrcType << TheOffendingDestType << qualifiers;
  2855. }
  2856. ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
  2857. TypeSourceInfo *CastTypeInfo,
  2858. SourceLocation RPLoc,
  2859. Expr *CastExpr) {
  2860. CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
  2861. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2862. Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
  2863. if (getLangOpts().CPlusPlus) {
  2864. Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
  2865. isa<InitListExpr>(CastExpr));
  2866. } else {
  2867. Op.CheckCStyleCast();
  2868. }
  2869. if (Op.SrcExpr.isInvalid())
  2870. return ExprError();
  2871. // -Wcast-qual
  2872. DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
  2873. return Op.complete(CStyleCastExpr::Create(
  2874. Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  2875. &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));
  2876. }
  2877. ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
  2878. QualType Type,
  2879. SourceLocation LPLoc,
  2880. Expr *CastExpr,
  2881. SourceLocation RPLoc) {
  2882. assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
  2883. CastOperation Op(*this, Type, CastExpr);
  2884. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2885. Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
  2886. Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
  2887. if (Op.SrcExpr.isInvalid())
  2888. return ExprError();
  2889. auto *SubExpr = Op.SrcExpr.get();
  2890. if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
  2891. SubExpr = BindExpr->getSubExpr();
  2892. if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
  2893. ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
  2894. return Op.complete(CXXFunctionalCastExpr::Create(
  2895. Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,
  2896. Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));
  2897. }