SemaCast.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518
  1. //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for cast expressions, including
  11. // 1) C-style casts like '(int) x'
  12. // 2) C++ functional casts like 'int(x)'
  13. // 3) C++ named casts like 'static_cast<int>(x)'
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/CXXInheritance.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/RecordLayout.h"
  22. #include "clang/Basic/PartialDiagnostic.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Sema/Initialization.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "clang/Sema/SemaHLSL.h" // HLSL Change
  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_Failed ///< The cast method is appropriate, but failed. A
  33. ///< diagnostic has been emitted.
  34. };
  35. enum CastType {
  36. CT_Const, ///< const_cast
  37. CT_Static, ///< static_cast
  38. CT_Reinterpret, ///< reinterpret_cast
  39. CT_Dynamic, ///< dynamic_cast
  40. CT_CStyle, ///< (Type)expr
  41. CT_Functional ///< Type(expr)
  42. };
  43. namespace {
  44. struct CastOperation {
  45. CastOperation(Sema &S, QualType destType, ExprResult src)
  46. : Self(S), SrcExpr(src), DestType(destType),
  47. ResultType(destType.getNonLValueExprType(S.Context)),
  48. ValueKind(Expr::getValueKindForType(destType)),
  49. Kind(CK_Dependent), IsARCUnbridgedCast(false) {
  50. if (const BuiltinType *placeholder =
  51. src.get()->getType()->getAsPlaceholderType()) {
  52. PlaceholderKind = placeholder->getKind();
  53. } else {
  54. PlaceholderKind = (BuiltinType::Kind) 0;
  55. }
  56. }
  57. Sema &Self;
  58. ExprResult SrcExpr;
  59. QualType DestType;
  60. QualType ResultType;
  61. ExprValueKind ValueKind;
  62. CastKind Kind;
  63. BuiltinType::Kind PlaceholderKind;
  64. CXXCastPath BasePath;
  65. bool IsARCUnbridgedCast;
  66. SourceRange OpRange;
  67. SourceRange DestRange;
  68. // Top-level semantics-checking routines.
  69. void CheckConstCast();
  70. void CheckReinterpretCast();
  71. void CheckStaticCast();
  72. void CheckDynamicCast();
  73. void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
  74. void CheckCStyleCast();
  75. /// Complete an apparently-successful cast operation that yields
  76. /// the given expression.
  77. ExprResult complete(CastExpr *castExpr) {
  78. // If this is an unbridged cast, wrap the result in an implicit
  79. // cast that yields the unbridged-cast placeholder type.
  80. if (IsARCUnbridgedCast) {
  81. castExpr = ImplicitCastExpr::Create(Self.Context,
  82. Self.Context.ARCUnbridgedCastTy,
  83. CK_Dependent, castExpr, nullptr,
  84. castExpr->getValueKind());
  85. }
  86. return castExpr;
  87. }
  88. // Internal convenience methods.
  89. /// Try to handle the given placeholder expression kind. Return
  90. /// true if the source expression has the appropriate placeholder
  91. /// kind. A placeholder can only be claimed once.
  92. bool claimPlaceholder(BuiltinType::Kind K) {
  93. if (PlaceholderKind != K) return false;
  94. PlaceholderKind = (BuiltinType::Kind) 0;
  95. return true;
  96. }
  97. bool isPlaceholder() const {
  98. return PlaceholderKind != 0;
  99. }
  100. bool isPlaceholder(BuiltinType::Kind K) const {
  101. return PlaceholderKind == K;
  102. }
  103. void checkCastAlign() {
  104. Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
  105. }
  106. void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
  107. assert(Self.getLangOpts().ObjCAutoRefCount);
  108. Expr *src = SrcExpr.get();
  109. if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
  110. Sema::ACR_unbridged)
  111. IsARCUnbridgedCast = true;
  112. SrcExpr = src;
  113. }
  114. /// Check for and handle non-overload placeholder expressions.
  115. void checkNonOverloadPlaceholders() {
  116. if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
  117. return;
  118. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  119. if (SrcExpr.isInvalid())
  120. return;
  121. PlaceholderKind = (BuiltinType::Kind) 0;
  122. }
  123. };
  124. }
  125. // The Try functions attempt a specific way of casting. If they succeed, they
  126. // return TC_Success. If their way of casting is not appropriate for the given
  127. // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
  128. // to emit if no other way succeeds. If their way of casting is appropriate but
  129. // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
  130. // they emit a specialized diagnostic.
  131. // All diagnostics returned by these functions must expect the same three
  132. // arguments:
  133. // %0: Cast Type (a value from the CastType enumeration)
  134. // %1: Source Type
  135. // %2: Destination Type
  136. static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
  137. QualType DestType, bool CStyle,
  138. CastKind &Kind,
  139. CXXCastPath &BasePath,
  140. unsigned &msg);
  141. static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
  142. QualType DestType, bool CStyle,
  143. const SourceRange &OpRange,
  144. unsigned &msg,
  145. CastKind &Kind,
  146. CXXCastPath &BasePath);
  147. static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
  148. QualType DestType, bool CStyle,
  149. const SourceRange &OpRange,
  150. unsigned &msg,
  151. CastKind &Kind,
  152. CXXCastPath &BasePath);
  153. static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
  154. CanQualType DestType, bool CStyle,
  155. const SourceRange &OpRange,
  156. QualType OrigSrcType,
  157. QualType OrigDestType, unsigned &msg,
  158. CastKind &Kind,
  159. CXXCastPath &BasePath);
  160. static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
  161. QualType SrcType,
  162. QualType DestType,bool CStyle,
  163. const SourceRange &OpRange,
  164. unsigned &msg,
  165. CastKind &Kind,
  166. CXXCastPath &BasePath);
  167. static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
  168. QualType DestType,
  169. Sema::CheckedConversionKind CCK,
  170. const SourceRange &OpRange,
  171. unsigned &msg, CastKind &Kind,
  172. bool ListInitialization);
  173. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  174. QualType DestType,
  175. Sema::CheckedConversionKind CCK,
  176. const SourceRange &OpRange,
  177. unsigned &msg, CastKind &Kind,
  178. CXXCastPath &BasePath,
  179. bool ListInitialization);
  180. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  181. QualType DestType, bool CStyle,
  182. unsigned &msg);
  183. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  184. QualType DestType, bool CStyle,
  185. const SourceRange &OpRange,
  186. unsigned &msg,
  187. CastKind &Kind);
  188. /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
  189. ExprResult
  190. Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  191. SourceLocation LAngleBracketLoc, Declarator &D,
  192. SourceLocation RAngleBracketLoc,
  193. SourceLocation LParenLoc, Expr *E,
  194. SourceLocation RParenLoc) {
  195. assert(!D.isInvalidType());
  196. TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
  197. if (D.isInvalidType())
  198. return ExprError();
  199. if (getLangOpts().CPlusPlus) {
  200. // Check that there are no default arguments (C++ only).
  201. CheckExtraCXXDefaultArguments(D);
  202. }
  203. return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
  204. SourceRange(LAngleBracketLoc, RAngleBracketLoc),
  205. SourceRange(LParenLoc, RParenLoc));
  206. }
  207. ExprResult
  208. Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
  209. TypeSourceInfo *DestTInfo, Expr *E,
  210. SourceRange AngleBrackets, SourceRange Parens) {
  211. ExprResult Ex = E;
  212. QualType DestType = DestTInfo->getType();
  213. // If the type is dependent, we won't do the semantic analysis now.
  214. bool TypeDependent =
  215. DestType->isDependentType() || Ex.get()->isTypeDependent();
  216. CastOperation Op(*this, DestType, E);
  217. Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
  218. Op.DestRange = AngleBrackets;
  219. switch (Kind) {
  220. default: llvm_unreachable("Unknown C++ cast!");
  221. case tok::kw_const_cast:
  222. if (!TypeDependent) {
  223. Op.CheckConstCast();
  224. if (Op.SrcExpr.isInvalid())
  225. return ExprError();
  226. }
  227. return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
  228. Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
  229. OpLoc, Parens.getEnd(),
  230. AngleBrackets));
  231. case tok::kw_dynamic_cast: {
  232. if (!TypeDependent) {
  233. Op.CheckDynamicCast();
  234. if (Op.SrcExpr.isInvalid())
  235. return ExprError();
  236. }
  237. return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
  238. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  239. &Op.BasePath, DestTInfo,
  240. OpLoc, Parens.getEnd(),
  241. AngleBrackets));
  242. }
  243. case tok::kw_reinterpret_cast: {
  244. if (!TypeDependent) {
  245. Op.CheckReinterpretCast();
  246. if (Op.SrcExpr.isInvalid())
  247. return ExprError();
  248. }
  249. return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
  250. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  251. nullptr, DestTInfo, OpLoc,
  252. Parens.getEnd(),
  253. AngleBrackets));
  254. }
  255. case tok::kw_static_cast: {
  256. if (!TypeDependent) {
  257. Op.CheckStaticCast();
  258. if (Op.SrcExpr.isInvalid())
  259. return ExprError();
  260. }
  261. return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
  262. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  263. &Op.BasePath, DestTInfo,
  264. OpLoc, Parens.getEnd(),
  265. AngleBrackets));
  266. }
  267. }
  268. }
  269. /// Try to diagnose a failed overloaded cast. Returns true if
  270. /// diagnostics were emitted.
  271. static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
  272. SourceRange range, Expr *src,
  273. QualType destType,
  274. bool listInitialization) {
  275. switch (CT) {
  276. // These cast kinds don't consider user-defined conversions.
  277. case CT_Const:
  278. case CT_Reinterpret:
  279. case CT_Dynamic:
  280. return false;
  281. // These do.
  282. case CT_Static:
  283. case CT_CStyle:
  284. case CT_Functional:
  285. break;
  286. }
  287. QualType srcType = src->getType();
  288. if (!destType->isRecordType() && !srcType->isRecordType())
  289. return false;
  290. InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
  291. InitializationKind initKind
  292. = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
  293. range, listInitialization)
  294. : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
  295. listInitialization)
  296. : InitializationKind::CreateCast(/*type range?*/ range);
  297. InitializationSequence sequence(S, entity, initKind, src);
  298. assert(sequence.Failed() && "initialization succeeded on second try?");
  299. switch (sequence.getFailureKind()) {
  300. default: return false;
  301. case InitializationSequence::FK_ConstructorOverloadFailed:
  302. case InitializationSequence::FK_UserConversionOverloadFailed:
  303. break;
  304. }
  305. OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
  306. unsigned msg = 0;
  307. OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
  308. switch (sequence.getFailedOverloadResult()) {
  309. case OR_Success: llvm_unreachable("successful failed overload");
  310. case OR_No_Viable_Function:
  311. if (candidates.empty())
  312. msg = diag::err_ovl_no_conversion_in_cast;
  313. else
  314. msg = diag::err_ovl_no_viable_conversion_in_cast;
  315. howManyCandidates = OCD_AllCandidates;
  316. break;
  317. case OR_Ambiguous:
  318. msg = diag::err_ovl_ambiguous_conversion_in_cast;
  319. howManyCandidates = OCD_ViableCandidates;
  320. break;
  321. case OR_Deleted:
  322. msg = diag::err_ovl_deleted_conversion_in_cast;
  323. howManyCandidates = OCD_ViableCandidates;
  324. break;
  325. }
  326. S.Diag(range.getBegin(), msg)
  327. << CT << srcType << destType
  328. << range << src->getSourceRange();
  329. candidates.NoteCandidates(S, howManyCandidates, src);
  330. return true;
  331. }
  332. /// Diagnose a failed cast.
  333. static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
  334. SourceRange opRange, Expr *src, QualType destType,
  335. bool listInitialization) {
  336. if (msg == diag::err_bad_cxx_cast_generic &&
  337. tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
  338. listInitialization))
  339. return;
  340. S.Diag(opRange.getBegin(), msg) << castType
  341. << src->getType() << destType << opRange << src->getSourceRange();
  342. // Detect if both types are (ptr to) class, and note any incompleteness.
  343. int DifferentPtrness = 0;
  344. QualType From = destType;
  345. if (auto Ptr = From->getAs<PointerType>()) {
  346. From = Ptr->getPointeeType();
  347. DifferentPtrness++;
  348. }
  349. QualType To = src->getType();
  350. if (auto Ptr = To->getAs<PointerType>()) {
  351. To = Ptr->getPointeeType();
  352. DifferentPtrness--;
  353. }
  354. if (!DifferentPtrness) {
  355. auto RecFrom = From->getAs<RecordType>();
  356. auto RecTo = To->getAs<RecordType>();
  357. if (RecFrom && RecTo) {
  358. auto DeclFrom = RecFrom->getAsCXXRecordDecl();
  359. if (!DeclFrom->isCompleteDefinition())
  360. S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
  361. << DeclFrom->getDeclName();
  362. auto DeclTo = RecTo->getAsCXXRecordDecl();
  363. if (!DeclTo->isCompleteDefinition())
  364. S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
  365. << DeclTo->getDeclName();
  366. }
  367. }
  368. }
  369. /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
  370. /// this removes one level of indirection from both types, provided that they're
  371. /// the same kind of pointer (plain or to-member). Unlike the Sema function,
  372. /// this one doesn't care if the two pointers-to-member don't point into the
  373. /// same class. This is because CastsAwayConstness doesn't care.
  374. static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
  375. const PointerType *T1PtrType = T1->getAs<PointerType>(),
  376. *T2PtrType = T2->getAs<PointerType>();
  377. if (T1PtrType && T2PtrType) {
  378. T1 = T1PtrType->getPointeeType();
  379. T2 = T2PtrType->getPointeeType();
  380. return true;
  381. }
  382. const ObjCObjectPointerType *T1ObjCPtrType =
  383. T1->getAs<ObjCObjectPointerType>(),
  384. *T2ObjCPtrType =
  385. T2->getAs<ObjCObjectPointerType>();
  386. if (T1ObjCPtrType) {
  387. if (T2ObjCPtrType) {
  388. T1 = T1ObjCPtrType->getPointeeType();
  389. T2 = T2ObjCPtrType->getPointeeType();
  390. return true;
  391. }
  392. else if (T2PtrType) {
  393. T1 = T1ObjCPtrType->getPointeeType();
  394. T2 = T2PtrType->getPointeeType();
  395. return true;
  396. }
  397. }
  398. else if (T2ObjCPtrType) {
  399. if (T1PtrType) {
  400. T2 = T2ObjCPtrType->getPointeeType();
  401. T1 = T1PtrType->getPointeeType();
  402. return true;
  403. }
  404. }
  405. const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
  406. *T2MPType = T2->getAs<MemberPointerType>();
  407. if (T1MPType && T2MPType) {
  408. T1 = T1MPType->getPointeeType();
  409. T2 = T2MPType->getPointeeType();
  410. return true;
  411. }
  412. const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
  413. *T2BPType = T2->getAs<BlockPointerType>();
  414. if (T1BPType && T2BPType) {
  415. T1 = T1BPType->getPointeeType();
  416. T2 = T2BPType->getPointeeType();
  417. return true;
  418. }
  419. return false;
  420. }
  421. /// CastsAwayConstness - Check if the pointer conversion from SrcType to
  422. /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
  423. /// the cast checkers. Both arguments must denote pointer (possibly to member)
  424. /// types.
  425. ///
  426. /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
  427. ///
  428. /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
  429. static bool
  430. CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
  431. bool CheckCVR, bool CheckObjCLifetime,
  432. QualType *TheOffendingSrcType = nullptr,
  433. QualType *TheOffendingDestType = nullptr,
  434. Qualifiers *CastAwayQualifiers = nullptr) {
  435. // If the only checking we care about is for Objective-C lifetime qualifiers,
  436. // and we're not in ARC mode, there's nothing to check.
  437. if (!CheckCVR && CheckObjCLifetime &&
  438. !Self.Context.getLangOpts().ObjCAutoRefCount)
  439. return false;
  440. // Casting away constness is defined in C++ 5.2.11p8 with reference to
  441. // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
  442. // the rules are non-trivial. So first we construct Tcv *...cv* as described
  443. // in C++ 5.2.11p8.
  444. assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
  445. SrcType->isBlockPointerType()) &&
  446. "Source type is not pointer or pointer to member.");
  447. assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
  448. DestType->isBlockPointerType()) &&
  449. "Destination type is not pointer or pointer to member.");
  450. QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
  451. UnwrappedDestType = Self.Context.getCanonicalType(DestType);
  452. SmallVector<Qualifiers, 8> cv1, cv2;
  453. // Find the qualifiers. We only care about cvr-qualifiers for the
  454. // purpose of this check, because other qualifiers (address spaces,
  455. // Objective-C GC, etc.) are part of the type's identity.
  456. QualType PrevUnwrappedSrcType = UnwrappedSrcType;
  457. QualType PrevUnwrappedDestType = UnwrappedDestType;
  458. while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
  459. // Determine the relevant qualifiers at this level.
  460. Qualifiers SrcQuals, DestQuals;
  461. Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
  462. Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
  463. Qualifiers RetainedSrcQuals, RetainedDestQuals;
  464. if (CheckCVR) {
  465. RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
  466. RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
  467. if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
  468. TheOffendingDestType && CastAwayQualifiers) {
  469. *TheOffendingSrcType = PrevUnwrappedSrcType;
  470. *TheOffendingDestType = PrevUnwrappedDestType;
  471. *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
  472. }
  473. }
  474. if (CheckObjCLifetime &&
  475. !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
  476. return true;
  477. cv1.push_back(RetainedSrcQuals);
  478. cv2.push_back(RetainedDestQuals);
  479. PrevUnwrappedSrcType = UnwrappedSrcType;
  480. PrevUnwrappedDestType = UnwrappedDestType;
  481. }
  482. if (cv1.empty())
  483. return false;
  484. // Construct void pointers with those qualifiers (in reverse order of
  485. // unwrapping, of course).
  486. QualType SrcConstruct = Self.Context.VoidTy;
  487. QualType DestConstruct = Self.Context.VoidTy;
  488. ASTContext &Context = Self.Context;
  489. for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
  490. i2 = cv2.rbegin();
  491. i1 != cv1.rend(); ++i1, ++i2) {
  492. SrcConstruct
  493. = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
  494. DestConstruct
  495. = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
  496. }
  497. // Test if they're compatible.
  498. bool ObjCLifetimeConversion;
  499. return SrcConstruct != DestConstruct &&
  500. !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
  501. ObjCLifetimeConversion);
  502. }
  503. /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
  504. /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
  505. /// checked downcasts in class hierarchies.
  506. void CastOperation::CheckDynamicCast() {
  507. if (ValueKind == VK_RValue)
  508. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  509. else if (isPlaceholder())
  510. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  511. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  512. return;
  513. QualType OrigSrcType = SrcExpr.get()->getType();
  514. QualType DestType = Self.Context.getCanonicalType(this->DestType);
  515. // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
  516. // or "pointer to cv void".
  517. QualType DestPointee;
  518. const PointerType *DestPointer = DestType->getAs<PointerType>();
  519. const ReferenceType *DestReference = nullptr;
  520. if (DestPointer) {
  521. DestPointee = DestPointer->getPointeeType();
  522. } else if ((DestReference = DestType->getAs<ReferenceType>())) {
  523. DestPointee = DestReference->getPointeeType();
  524. } else {
  525. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
  526. << this->DestType << DestRange;
  527. SrcExpr = ExprError();
  528. return;
  529. }
  530. const RecordType *DestRecord = DestPointee->getAs<RecordType>();
  531. if (DestPointee->isVoidType()) {
  532. assert(DestPointer && "Reference to void is not possible");
  533. } else if (DestRecord) {
  534. if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
  535. diag::err_bad_dynamic_cast_incomplete,
  536. DestRange)) {
  537. SrcExpr = ExprError();
  538. return;
  539. }
  540. } else {
  541. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  542. << DestPointee.getUnqualifiedType() << DestRange;
  543. SrcExpr = ExprError();
  544. return;
  545. }
  546. // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
  547. // complete class type, [...]. If T is an lvalue reference type, v shall be
  548. // an lvalue of a complete class type, [...]. If T is an rvalue reference
  549. // type, v shall be an expression having a complete class type, [...]
  550. QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
  551. QualType SrcPointee;
  552. if (DestPointer) {
  553. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  554. SrcPointee = SrcPointer->getPointeeType();
  555. } else {
  556. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
  557. << OrigSrcType << SrcExpr.get()->getSourceRange();
  558. SrcExpr = ExprError();
  559. return;
  560. }
  561. } else if (DestReference->isLValueReferenceType()) {
  562. if (!SrcExpr.get()->isLValue()) {
  563. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
  564. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  565. }
  566. SrcPointee = SrcType;
  567. } else {
  568. // If we're dynamic_casting from a prvalue to an rvalue reference, we need
  569. // to materialize the prvalue before we bind the reference to it.
  570. if (SrcExpr.get()->isRValue())
  571. SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
  572. SrcType, SrcExpr.get(), /*IsLValueReference*/false);
  573. SrcPointee = SrcType;
  574. }
  575. const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
  576. if (SrcRecord) {
  577. if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
  578. diag::err_bad_dynamic_cast_incomplete,
  579. SrcExpr.get())) {
  580. SrcExpr = ExprError();
  581. return;
  582. }
  583. } else {
  584. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
  585. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  586. SrcExpr = ExprError();
  587. return;
  588. }
  589. assert((DestPointer || DestReference) &&
  590. "Bad destination non-ptr/ref slipped through.");
  591. assert((DestRecord || DestPointee->isVoidType()) &&
  592. "Bad destination pointee slipped through.");
  593. assert(SrcRecord && "Bad source pointee slipped through.");
  594. // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
  595. if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
  596. Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
  597. << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
  598. SrcExpr = ExprError();
  599. return;
  600. }
  601. // C++ 5.2.7p3: If the type of v is the same as the required result type,
  602. // [except for cv].
  603. if (DestRecord == SrcRecord) {
  604. Kind = CK_NoOp;
  605. return;
  606. }
  607. // C++ 5.2.7p5
  608. // Upcasts are resolved statically.
  609. if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
  610. if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
  611. OpRange.getBegin(), OpRange,
  612. &BasePath)) {
  613. SrcExpr = ExprError();
  614. return;
  615. }
  616. Kind = CK_DerivedToBase;
  617. return;
  618. }
  619. // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
  620. const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
  621. assert(SrcDecl && "Definition missing");
  622. if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
  623. Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
  624. << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
  625. SrcExpr = ExprError();
  626. }
  627. // dynamic_cast is not available with -fno-rtti.
  628. // As an exception, dynamic_cast to void* is available because it doesn't
  629. // use RTTI.
  630. if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
  631. Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
  632. SrcExpr = ExprError();
  633. return;
  634. }
  635. // Done. Everything else is run-time checks.
  636. Kind = CK_Dynamic;
  637. }
  638. /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
  639. /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
  640. /// like this:
  641. /// const char *str = "literal";
  642. /// legacy_function(const_cast\<char*\>(str));
  643. void CastOperation::CheckConstCast() {
  644. if (ValueKind == VK_RValue)
  645. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  646. else if (isPlaceholder())
  647. SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
  648. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  649. return;
  650. unsigned msg = diag::err_bad_cxx_cast_generic;
  651. if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
  652. && msg != 0) {
  653. Self.Diag(OpRange.getBegin(), msg) << CT_Const
  654. << SrcExpr.get()->getType() << DestType << OpRange;
  655. SrcExpr = ExprError();
  656. }
  657. }
  658. /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
  659. /// or downcast between respective pointers or references.
  660. static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
  661. QualType DestType,
  662. SourceRange OpRange) {
  663. QualType SrcType = SrcExpr->getType();
  664. // When casting from pointer or reference, get pointee type; use original
  665. // type otherwise.
  666. const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
  667. const CXXRecordDecl *SrcRD =
  668. SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
  669. // Examining subobjects for records is only possible if the complete and
  670. // valid definition is available. Also, template instantiation is not
  671. // allowed here.
  672. if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
  673. return;
  674. const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
  675. if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
  676. return;
  677. enum {
  678. ReinterpretUpcast,
  679. ReinterpretDowncast
  680. } ReinterpretKind;
  681. CXXBasePaths BasePaths;
  682. if (SrcRD->isDerivedFrom(DestRD, BasePaths))
  683. ReinterpretKind = ReinterpretUpcast;
  684. else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
  685. ReinterpretKind = ReinterpretDowncast;
  686. else
  687. return;
  688. bool VirtualBase = true;
  689. bool NonZeroOffset = false;
  690. for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
  691. E = BasePaths.end();
  692. I != E; ++I) {
  693. const CXXBasePath &Path = *I;
  694. CharUnits Offset = CharUnits::Zero();
  695. bool IsVirtual = false;
  696. for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
  697. IElem != EElem; ++IElem) {
  698. IsVirtual = IElem->Base->isVirtual();
  699. if (IsVirtual)
  700. break;
  701. const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
  702. assert(BaseRD && "Base type should be a valid unqualified class type");
  703. // Don't check if any base has invalid declaration or has no definition
  704. // since it has no layout info.
  705. const CXXRecordDecl *Class = IElem->Class,
  706. *ClassDefinition = Class->getDefinition();
  707. if (Class->isInvalidDecl() || !ClassDefinition ||
  708. !ClassDefinition->isCompleteDefinition())
  709. return;
  710. const ASTRecordLayout &DerivedLayout =
  711. Self.Context.getASTRecordLayout(Class);
  712. Offset += DerivedLayout.getBaseClassOffset(BaseRD);
  713. }
  714. if (!IsVirtual) {
  715. // Don't warn if any path is a non-virtually derived base at offset zero.
  716. if (Offset.isZero())
  717. return;
  718. // Offset makes sense only for non-virtual bases.
  719. else
  720. NonZeroOffset = true;
  721. }
  722. VirtualBase = VirtualBase && IsVirtual;
  723. }
  724. (void) NonZeroOffset; // Silence set but not used warning.
  725. assert((VirtualBase || NonZeroOffset) &&
  726. "Should have returned if has non-virtual base with zero offset");
  727. QualType BaseType =
  728. ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
  729. QualType DerivedType =
  730. ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
  731. SourceLocation BeginLoc = OpRange.getBegin();
  732. Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
  733. << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
  734. << OpRange;
  735. Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
  736. << int(ReinterpretKind)
  737. << FixItHint::CreateReplacement(BeginLoc, "static_cast");
  738. }
  739. /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
  740. /// valid.
  741. /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
  742. /// like this:
  743. /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
  744. void CastOperation::CheckReinterpretCast() {
  745. if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
  746. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  747. else
  748. checkNonOverloadPlaceholders();
  749. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  750. return;
  751. unsigned msg = diag::err_bad_cxx_cast_generic;
  752. TryCastResult tcr =
  753. TryReinterpretCast(Self, SrcExpr, DestType,
  754. /*CStyle*/false, OpRange, msg, Kind);
  755. if (tcr != TC_Success && msg != 0)
  756. {
  757. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  758. return;
  759. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  760. //FIXME: &f<int>; is overloaded and resolvable
  761. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
  762. << OverloadExpr::find(SrcExpr.get()).Expression->getName()
  763. << DestType << OpRange;
  764. Self.NoteAllOverloadCandidates(SrcExpr.get());
  765. } else {
  766. diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
  767. DestType, /*listInitialization=*/false);
  768. }
  769. SrcExpr = ExprError();
  770. } else if (tcr == TC_Success) {
  771. if (Self.getLangOpts().ObjCAutoRefCount)
  772. checkObjCARCConversion(Sema::CCK_OtherCast);
  773. DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
  774. }
  775. }
  776. /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
  777. /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
  778. /// implicit conversions explicit and getting rid of data loss warnings.
  779. void CastOperation::CheckStaticCast() {
  780. if (isPlaceholder()) {
  781. checkNonOverloadPlaceholders();
  782. if (SrcExpr.isInvalid())
  783. return;
  784. }
  785. // This test is outside everything else because it's the only case where
  786. // a non-lvalue-reference target type does not lead to decay.
  787. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  788. if (DestType->isVoidType()) {
  789. Kind = CK_ToVoid;
  790. if (claimPlaceholder(BuiltinType::Overload)) {
  791. Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
  792. false, // Decay Function to ptr
  793. true, // Complain
  794. OpRange, DestType, diag::err_bad_static_cast_overload);
  795. if (SrcExpr.isInvalid())
  796. return;
  797. }
  798. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  799. return;
  800. }
  801. if (ValueKind == VK_RValue && !DestType->isRecordType() &&
  802. !isPlaceholder(BuiltinType::Overload)
  803. && !(Self.getLangOpts().HLSL && !hlsl::IsConversionToLessOrEqualElements(&Self, SrcExpr, DestType, true)) // HLSL Change: check for HLSL vector-shrinking.
  804. ) {
  805. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  806. if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
  807. return;
  808. }
  809. unsigned msg = diag::err_bad_cxx_cast_generic;
  810. TryCastResult tcr
  811. = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
  812. Kind, BasePath, /*ListInitialization=*/false);
  813. if (tcr != TC_Success && msg != 0) {
  814. if (SrcExpr.isInvalid())
  815. return;
  816. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  817. OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
  818. Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
  819. << oe->getName() << DestType << OpRange
  820. << oe->getQualifierLoc().getSourceRange();
  821. Self.NoteAllOverloadCandidates(SrcExpr.get());
  822. } else {
  823. diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
  824. /*listInitialization=*/false);
  825. }
  826. SrcExpr = ExprError();
  827. } else if (tcr == TC_Success) {
  828. if (Kind == CK_BitCast)
  829. checkCastAlign();
  830. if (Self.getLangOpts().ObjCAutoRefCount)
  831. checkObjCARCConversion(Sema::CCK_OtherCast);
  832. } else if (Kind == CK_BitCast) {
  833. checkCastAlign();
  834. }
  835. }
  836. /// TryStaticCast - Check if a static cast can be performed, and do so if
  837. /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
  838. /// and casting away constness.
  839. static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
  840. QualType DestType,
  841. Sema::CheckedConversionKind CCK,
  842. const SourceRange &OpRange, unsigned &msg,
  843. CastKind &Kind, CXXCastPath &BasePath,
  844. bool ListInitialization) {
  845. // Determine whether we have the semantics of a C-style cast.
  846. bool CStyle
  847. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  848. // The order the tests is not entirely arbitrary. There is one conversion
  849. // that can be handled in two different ways. Given:
  850. // struct A {};
  851. // struct B : public A {
  852. // B(); B(const A&);
  853. // };
  854. // const A &a = B();
  855. // the cast static_cast<const B&>(a) could be seen as either a static
  856. // reference downcast, or an explicit invocation of the user-defined
  857. // conversion using B's conversion constructor.
  858. // DR 427 specifies that the downcast is to be applied here.
  859. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  860. // Done outside this function.
  861. TryCastResult tcr;
  862. // C++ 5.2.9p5, reference downcast.
  863. // See the function for details.
  864. // DR 427 specifies that this is to be applied before paragraph 2.
  865. tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
  866. OpRange, msg, Kind, BasePath);
  867. if (tcr != TC_NotApplicable)
  868. return tcr;
  869. // C++11 [expr.static.cast]p3:
  870. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
  871. // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  872. tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
  873. BasePath, msg);
  874. if (tcr != TC_NotApplicable)
  875. return tcr;
  876. // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
  877. // [...] if the declaration "T t(e);" is well-formed, [...].
  878. tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
  879. Kind, ListInitialization);
  880. if (SrcExpr.isInvalid())
  881. return TC_Failed;
  882. if (tcr != TC_NotApplicable)
  883. return tcr;
  884. // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
  885. // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
  886. // conversions, subject to further restrictions.
  887. // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
  888. // of qualification conversions impossible.
  889. // In the CStyle case, the earlier attempt to const_cast should have taken
  890. // care of reverse qualification conversions.
  891. QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
  892. // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
  893. // converted to an integral type. [...] A value of a scoped enumeration type
  894. // can also be explicitly converted to a floating-point type [...].
  895. if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
  896. if (Enum->getDecl()->isScoped()) {
  897. if (DestType->isBooleanType()) {
  898. Kind = CK_IntegralToBoolean;
  899. return TC_Success;
  900. } else if (DestType->isIntegralType(Self.Context)) {
  901. Kind = CK_IntegralCast;
  902. return TC_Success;
  903. } else if (DestType->isRealFloatingType()) {
  904. Kind = CK_IntegralToFloating;
  905. return TC_Success;
  906. }
  907. }
  908. }
  909. // Reverse integral promotion/conversion. All such conversions are themselves
  910. // again integral promotions or conversions and are thus already handled by
  911. // p2 (TryDirectInitialization above).
  912. // (Note: any data loss warnings should be suppressed.)
  913. // The exception is the reverse of enum->integer, i.e. integer->enum (and
  914. // enum->enum). See also C++ 5.2.9p7.
  915. // The same goes for reverse floating point promotion/conversion and
  916. // floating-integral conversions. Again, only floating->enum is relevant.
  917. if (DestType->isEnumeralType()) {
  918. if (SrcType->isIntegralOrEnumerationType()) {
  919. Kind = CK_IntegralCast;
  920. return TC_Success;
  921. } else if (SrcType->isRealFloatingType()) {
  922. Kind = CK_FloatingToIntegral;
  923. return TC_Success;
  924. }
  925. }
  926. // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
  927. // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
  928. tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
  929. Kind, BasePath);
  930. if (tcr != TC_NotApplicable)
  931. return tcr;
  932. // Reverse member pointer conversion. C++ 4.11 specifies member pointer
  933. // conversion. C++ 5.2.9p9 has additional information.
  934. // DR54's access restrictions apply here also.
  935. tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
  936. OpRange, msg, Kind, BasePath);
  937. if (tcr != TC_NotApplicable)
  938. return tcr;
  939. // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
  940. // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
  941. // just the usual constness stuff.
  942. if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
  943. QualType SrcPointee = SrcPointer->getPointeeType();
  944. if (SrcPointee->isVoidType()) {
  945. if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
  946. QualType DestPointee = DestPointer->getPointeeType();
  947. if (DestPointee->isIncompleteOrObjectType()) {
  948. // This is definitely the intended conversion, but it might fail due
  949. // to a qualifier violation. Note that we permit Objective-C lifetime
  950. // and GC qualifier mismatches here.
  951. if (!CStyle) {
  952. Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
  953. Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
  954. DestPointeeQuals.removeObjCGCAttr();
  955. DestPointeeQuals.removeObjCLifetime();
  956. SrcPointeeQuals.removeObjCGCAttr();
  957. SrcPointeeQuals.removeObjCLifetime();
  958. if (DestPointeeQuals != SrcPointeeQuals &&
  959. !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
  960. msg = diag::err_bad_cxx_cast_qualifiers_away;
  961. return TC_Failed;
  962. }
  963. }
  964. Kind = CK_BitCast;
  965. return TC_Success;
  966. }
  967. // Microsoft permits static_cast from 'pointer-to-void' to
  968. // 'pointer-to-function'.
  969. if (!CStyle && Self.getLangOpts().MSVCCompat &&
  970. DestPointee->isFunctionType()) {
  971. Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
  972. Kind = CK_BitCast;
  973. return TC_Success;
  974. }
  975. }
  976. else if (DestType->isObjCObjectPointerType()) {
  977. // allow both c-style cast and static_cast of objective-c pointers as
  978. // they are pervasive.
  979. Kind = CK_CPointerToObjCPointerCast;
  980. return TC_Success;
  981. }
  982. else if (CStyle && DestType->isBlockPointerType()) {
  983. // allow c-style cast of void * to block pointers.
  984. Kind = CK_AnyPointerToBlockPointerCast;
  985. return TC_Success;
  986. }
  987. }
  988. }
  989. // Allow arbitray objective-c pointer conversion with static casts.
  990. if (SrcType->isObjCObjectPointerType() &&
  991. DestType->isObjCObjectPointerType()) {
  992. Kind = CK_BitCast;
  993. return TC_Success;
  994. }
  995. // Allow ns-pointer to cf-pointer conversion in either direction
  996. // with static casts.
  997. if (!CStyle &&
  998. Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
  999. return TC_Success;
  1000. // See if it looks like the user is trying to convert between
  1001. // related record types, and select a better diagnostic if so.
  1002. if (auto SrcPointer = SrcType->getAs<PointerType>())
  1003. if (auto DestPointer = DestType->getAs<PointerType>())
  1004. if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
  1005. DestPointer->getPointeeType()->getAs<RecordType>())
  1006. msg = diag::err_bad_cxx_cast_unrelated_class;
  1007. // HLSL Change Starts
  1008. if (Self.getLangOpts().HLSL) {
  1009. const bool SuppressDiagFalse = false;
  1010. if (hlsl::TryStaticCastForHLSL(&Self, SrcExpr, DestType, CCK, OpRange, msg,
  1011. Kind, BasePath, ListInitialization,
  1012. SuppressDiagFalse, nullptr)) {
  1013. return TC_Success;
  1014. }
  1015. }
  1016. // HLSL Change Ends
  1017. // We tried everything. Everything! Nothing works! :-(
  1018. return TC_NotApplicable;
  1019. }
  1020. /// Tests whether a conversion according to N2844 is valid.
  1021. TryCastResult
  1022. TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
  1023. bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
  1024. unsigned &msg) {
  1025. // C++11 [expr.static.cast]p3:
  1026. // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
  1027. // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
  1028. const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
  1029. if (!R)
  1030. return TC_NotApplicable;
  1031. if (!SrcExpr->isGLValue())
  1032. return TC_NotApplicable;
  1033. // Because we try the reference downcast before this function, from now on
  1034. // this is the only cast possibility, so we issue an error if we fail now.
  1035. // FIXME: Should allow casting away constness if CStyle.
  1036. bool DerivedToBase;
  1037. bool ObjCConversion;
  1038. bool ObjCLifetimeConversion;
  1039. QualType FromType = SrcExpr->getType();
  1040. QualType ToType = R->getPointeeType();
  1041. if (CStyle) {
  1042. FromType = FromType.getUnqualifiedType();
  1043. ToType = ToType.getUnqualifiedType();
  1044. }
  1045. if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
  1046. ToType, FromType,
  1047. DerivedToBase, ObjCConversion,
  1048. ObjCLifetimeConversion)
  1049. < Sema::Ref_Compatible_With_Added_Qualification) {
  1050. if (CStyle)
  1051. return TC_NotApplicable;
  1052. msg = diag::err_bad_lvalue_to_rvalue_cast;
  1053. return TC_Failed;
  1054. }
  1055. if (DerivedToBase) {
  1056. Kind = CK_DerivedToBase;
  1057. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1058. /*DetectVirtual=*/true);
  1059. if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
  1060. return TC_NotApplicable;
  1061. Self.BuildBasePathArray(Paths, BasePath);
  1062. } else
  1063. Kind = CK_NoOp;
  1064. return TC_Success;
  1065. }
  1066. /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
  1067. TryCastResult
  1068. TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
  1069. bool CStyle, const SourceRange &OpRange,
  1070. unsigned &msg, CastKind &Kind,
  1071. CXXCastPath &BasePath) {
  1072. // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
  1073. // cast to type "reference to cv2 D", where D is a class derived from B,
  1074. // if a valid standard conversion from "pointer to D" to "pointer to B"
  1075. // exists, cv2 >= cv1, and B is not a virtual base class of D.
  1076. // In addition, DR54 clarifies that the base must be accessible in the
  1077. // current context. Although the wording of DR54 only applies to the pointer
  1078. // variant of this rule, the intent is clearly for it to apply to the this
  1079. // conversion as well.
  1080. const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
  1081. if (!DestReference) {
  1082. return TC_NotApplicable;
  1083. }
  1084. bool RValueRef = DestReference->isRValueReferenceType();
  1085. if (!RValueRef && !SrcExpr->isLValue()) {
  1086. // We know the left side is an lvalue reference, so we can suggest a reason.
  1087. msg = diag::err_bad_cxx_cast_rvalue;
  1088. return TC_NotApplicable;
  1089. }
  1090. QualType DestPointee = DestReference->getPointeeType();
  1091. // FIXME: If the source is a prvalue, we should issue a warning (because the
  1092. // cast always has undefined behavior), and for AST consistency, we should
  1093. // materialize a temporary.
  1094. return TryStaticDowncast(Self,
  1095. Self.Context.getCanonicalType(SrcExpr->getType()),
  1096. Self.Context.getCanonicalType(DestPointee), CStyle,
  1097. OpRange, SrcExpr->getType(), DestType, msg, Kind,
  1098. BasePath);
  1099. }
  1100. /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
  1101. TryCastResult
  1102. TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
  1103. bool CStyle, const SourceRange &OpRange,
  1104. unsigned &msg, CastKind &Kind,
  1105. CXXCastPath &BasePath) {
  1106. // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
  1107. // type, can be converted to an rvalue of type "pointer to cv2 D", where D
  1108. // is a class derived from B, if a valid standard conversion from "pointer
  1109. // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
  1110. // class of D.
  1111. // In addition, DR54 clarifies that the base must be accessible in the
  1112. // current context.
  1113. const PointerType *DestPointer = DestType->getAs<PointerType>();
  1114. if (!DestPointer) {
  1115. return TC_NotApplicable;
  1116. }
  1117. const PointerType *SrcPointer = SrcType->getAs<PointerType>();
  1118. if (!SrcPointer) {
  1119. msg = diag::err_bad_static_cast_pointer_nonpointer;
  1120. return TC_NotApplicable;
  1121. }
  1122. return TryStaticDowncast(Self,
  1123. Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
  1124. Self.Context.getCanonicalType(DestPointer->getPointeeType()),
  1125. CStyle, OpRange, SrcType, DestType, msg, Kind,
  1126. BasePath);
  1127. }
  1128. /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
  1129. /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
  1130. /// DestType is possible and allowed.
  1131. TryCastResult
  1132. TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
  1133. bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
  1134. QualType OrigDestType, unsigned &msg,
  1135. CastKind &Kind, CXXCastPath &BasePath) {
  1136. // We can only work with complete types. But don't complain if it doesn't work
  1137. if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
  1138. Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
  1139. return TC_NotApplicable;
  1140. // Downcast can only happen in class hierarchies, so we need classes.
  1141. if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
  1142. return TC_NotApplicable;
  1143. }
  1144. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1145. /*DetectVirtual=*/true);
  1146. if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
  1147. return TC_NotApplicable;
  1148. }
  1149. // Target type does derive from source type. Now we're serious. If an error
  1150. // appears now, it's not ignored.
  1151. // This may not be entirely in line with the standard. Take for example:
  1152. // struct A {};
  1153. // struct B : virtual A {
  1154. // B(A&);
  1155. // };
  1156. //
  1157. // void f()
  1158. // {
  1159. // (void)static_cast<const B&>(*((A*)0));
  1160. // }
  1161. // As far as the standard is concerned, p5 does not apply (A is virtual), so
  1162. // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
  1163. // However, both GCC and Comeau reject this example, and accepting it would
  1164. // mean more complex code if we're to preserve the nice error message.
  1165. // FIXME: Being 100% compliant here would be nice to have.
  1166. // Must preserve cv, as always, unless we're in C-style mode.
  1167. if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
  1168. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1169. return TC_Failed;
  1170. }
  1171. if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
  1172. // This code is analoguous to that in CheckDerivedToBaseConversion, except
  1173. // that it builds the paths in reverse order.
  1174. // To sum up: record all paths to the base and build a nice string from
  1175. // them. Use it to spice up the error message.
  1176. if (!Paths.isRecordingPaths()) {
  1177. Paths.clear();
  1178. Paths.setRecordingPaths(true);
  1179. Self.IsDerivedFrom(DestType, SrcType, Paths);
  1180. }
  1181. std::string PathDisplayStr;
  1182. std::set<unsigned> DisplayedPaths;
  1183. for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
  1184. PI != PE; ++PI) {
  1185. if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
  1186. // We haven't displayed a path to this particular base
  1187. // class subobject yet.
  1188. PathDisplayStr += "\n ";
  1189. for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
  1190. EE = PI->rend();
  1191. EI != EE; ++EI)
  1192. PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
  1193. PathDisplayStr += QualType(DestType).getAsString();
  1194. }
  1195. }
  1196. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
  1197. << QualType(SrcType).getUnqualifiedType()
  1198. << QualType(DestType).getUnqualifiedType()
  1199. << PathDisplayStr << OpRange;
  1200. msg = 0;
  1201. return TC_Failed;
  1202. }
  1203. if (Paths.getDetectedVirtual() != nullptr) {
  1204. QualType VirtualBase(Paths.getDetectedVirtual(), 0);
  1205. Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
  1206. << OrigSrcType << OrigDestType << VirtualBase << OpRange;
  1207. msg = 0;
  1208. return TC_Failed;
  1209. }
  1210. if (!CStyle) {
  1211. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1212. SrcType, DestType,
  1213. Paths.front(),
  1214. diag::err_downcast_from_inaccessible_base)) {
  1215. case Sema::AR_accessible:
  1216. case Sema::AR_delayed: // be optimistic
  1217. case Sema::AR_dependent: // be optimistic
  1218. break;
  1219. case Sema::AR_inaccessible:
  1220. msg = 0;
  1221. return TC_Failed;
  1222. }
  1223. }
  1224. Self.BuildBasePathArray(Paths, BasePath);
  1225. Kind = CK_BaseToDerived;
  1226. return TC_Success;
  1227. }
  1228. /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
  1229. /// C++ 5.2.9p9 is valid:
  1230. ///
  1231. /// An rvalue of type "pointer to member of D of type cv1 T" can be
  1232. /// converted to an rvalue of type "pointer to member of B of type cv2 T",
  1233. /// where B is a base class of D [...].
  1234. ///
  1235. TryCastResult
  1236. TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
  1237. QualType DestType, bool CStyle,
  1238. const SourceRange &OpRange,
  1239. unsigned &msg, CastKind &Kind,
  1240. CXXCastPath &BasePath) {
  1241. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
  1242. if (!DestMemPtr)
  1243. return TC_NotApplicable;
  1244. bool WasOverloadedFunction = false;
  1245. DeclAccessPair FoundOverload;
  1246. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1247. if (FunctionDecl *Fn
  1248. = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
  1249. FoundOverload)) {
  1250. CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
  1251. SrcType = Self.Context.getMemberPointerType(Fn->getType(),
  1252. Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
  1253. WasOverloadedFunction = true;
  1254. }
  1255. }
  1256. const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1257. if (!SrcMemPtr) {
  1258. msg = diag::err_bad_static_cast_member_pointer_nonmp;
  1259. return TC_NotApplicable;
  1260. }
  1261. // T == T, modulo cv
  1262. if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
  1263. DestMemPtr->getPointeeType()))
  1264. return TC_NotApplicable;
  1265. // B base of D
  1266. QualType SrcClass(SrcMemPtr->getClass(), 0);
  1267. QualType DestClass(DestMemPtr->getClass(), 0);
  1268. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  1269. /*DetectVirtual=*/true);
  1270. if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
  1271. !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
  1272. return TC_NotApplicable;
  1273. }
  1274. // B is a base of D. But is it an allowed base? If not, it's a hard error.
  1275. if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
  1276. Paths.clear();
  1277. Paths.setRecordingPaths(true);
  1278. bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
  1279. assert(StillOkay);
  1280. (void)StillOkay;
  1281. std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
  1282. Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
  1283. << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
  1284. msg = 0;
  1285. return TC_Failed;
  1286. }
  1287. if (const RecordType *VBase = Paths.getDetectedVirtual()) {
  1288. Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
  1289. << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
  1290. msg = 0;
  1291. return TC_Failed;
  1292. }
  1293. if (!CStyle) {
  1294. switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
  1295. DestClass, SrcClass,
  1296. Paths.front(),
  1297. diag::err_upcast_to_inaccessible_base)) {
  1298. case Sema::AR_accessible:
  1299. case Sema::AR_delayed:
  1300. case Sema::AR_dependent:
  1301. // Optimistically assume that the delayed and dependent cases
  1302. // will work out.
  1303. break;
  1304. case Sema::AR_inaccessible:
  1305. msg = 0;
  1306. return TC_Failed;
  1307. }
  1308. }
  1309. if (WasOverloadedFunction) {
  1310. // Resolve the address of the overloaded function again, this time
  1311. // allowing complaints if something goes wrong.
  1312. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  1313. DestType,
  1314. true,
  1315. FoundOverload);
  1316. if (!Fn) {
  1317. msg = 0;
  1318. return TC_Failed;
  1319. }
  1320. SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
  1321. if (!SrcExpr.isUsable()) {
  1322. msg = 0;
  1323. return TC_Failed;
  1324. }
  1325. }
  1326. Self.BuildBasePathArray(Paths, BasePath);
  1327. Kind = CK_DerivedToBaseMemberPointer;
  1328. return TC_Success;
  1329. }
  1330. /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
  1331. /// is valid:
  1332. ///
  1333. /// An expression e can be explicitly converted to a type T using a
  1334. /// @c static_cast if the declaration "T t(e);" is well-formed [...].
  1335. TryCastResult
  1336. TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
  1337. Sema::CheckedConversionKind CCK,
  1338. const SourceRange &OpRange, unsigned &msg,
  1339. CastKind &Kind, bool ListInitialization) {
  1340. if (DestType->isRecordType()) {
  1341. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  1342. diag::err_bad_dynamic_cast_incomplete) ||
  1343. Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
  1344. diag::err_allocation_of_abstract_type)) {
  1345. msg = 0;
  1346. return TC_Failed;
  1347. }
  1348. } else if (DestType->isMemberPointerType()) {
  1349. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1350. Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
  1351. }
  1352. }
  1353. InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
  1354. InitializationKind InitKind
  1355. = (CCK == Sema::CCK_CStyleCast)
  1356. ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
  1357. ListInitialization)
  1358. : (CCK == Sema::CCK_FunctionalCast)
  1359. ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
  1360. : InitializationKind::CreateCast(OpRange);
  1361. Expr *SrcExprRaw = SrcExpr.get();
  1362. InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
  1363. // At this point of CheckStaticCast, if the destination is a reference,
  1364. // or the expression is an overload expression this has to work.
  1365. // There is no other way that works.
  1366. // On the other hand, if we're checking a C-style cast, we've still got
  1367. // the reinterpret_cast way.
  1368. bool CStyle
  1369. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  1370. if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
  1371. return TC_NotApplicable;
  1372. ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
  1373. if (Result.isInvalid()) {
  1374. msg = 0;
  1375. return TC_Failed;
  1376. }
  1377. if (InitSeq.isConstructorInitialization())
  1378. Kind = CK_ConstructorConversion;
  1379. else
  1380. Kind = CK_NoOp;
  1381. SrcExpr = Result;
  1382. return TC_Success;
  1383. }
  1384. /// TryConstCast - See if a const_cast from source to destination is allowed,
  1385. /// and perform it if it is.
  1386. static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
  1387. QualType DestType, bool CStyle,
  1388. unsigned &msg) {
  1389. DestType = Self.Context.getCanonicalType(DestType);
  1390. QualType SrcType = SrcExpr.get()->getType();
  1391. bool NeedToMaterializeTemporary = false;
  1392. if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
  1393. // C++11 5.2.11p4:
  1394. // if a pointer to T1 can be explicitly converted to the type "pointer to
  1395. // T2" using a const_cast, then the following conversions can also be
  1396. // made:
  1397. // -- an lvalue of type T1 can be explicitly converted to an lvalue of
  1398. // type T2 using the cast const_cast<T2&>;
  1399. // -- a glvalue of type T1 can be explicitly converted to an xvalue of
  1400. // type T2 using the cast const_cast<T2&&>; and
  1401. // -- if T1 is a class type, a prvalue of type T1 can be explicitly
  1402. // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
  1403. if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
  1404. // Cannot const_cast non-lvalue to lvalue reference type. But if this
  1405. // is C-style, static_cast might find a way, so we simply suggest a
  1406. // message and tell the parent to keep searching.
  1407. msg = diag::err_bad_cxx_cast_rvalue;
  1408. return TC_NotApplicable;
  1409. }
  1410. if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
  1411. if (!SrcType->isRecordType()) {
  1412. // Cannot const_cast non-class prvalue to rvalue reference type. But if
  1413. // this is C-style, static_cast can do this.
  1414. msg = diag::err_bad_cxx_cast_rvalue;
  1415. return TC_NotApplicable;
  1416. }
  1417. // Materialize the class prvalue so that the const_cast can bind a
  1418. // reference to it.
  1419. NeedToMaterializeTemporary = true;
  1420. }
  1421. // It's not completely clear under the standard whether we can
  1422. // const_cast bit-field gl-values. Doing so would not be
  1423. // intrinsically complicated, but for now, we say no for
  1424. // consistency with other compilers and await the word of the
  1425. // committee.
  1426. if (SrcExpr.get()->refersToBitField()) {
  1427. msg = diag::err_bad_cxx_cast_bitfield;
  1428. return TC_NotApplicable;
  1429. }
  1430. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1431. SrcType = Self.Context.getPointerType(SrcType);
  1432. }
  1433. // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
  1434. // the rules for const_cast are the same as those used for pointers.
  1435. if (!DestType->isPointerType() &&
  1436. !DestType->isMemberPointerType() &&
  1437. !DestType->isObjCObjectPointerType()) {
  1438. // Cannot cast to non-pointer, non-reference type. Note that, if DestType
  1439. // was a reference type, we converted it to a pointer above.
  1440. // The status of rvalue references isn't entirely clear, but it looks like
  1441. // conversion to them is simply invalid.
  1442. // C++ 5.2.11p3: For two pointer types [...]
  1443. if (!CStyle)
  1444. msg = diag::err_bad_const_cast_dest;
  1445. return TC_NotApplicable;
  1446. }
  1447. if (DestType->isFunctionPointerType() ||
  1448. DestType->isMemberFunctionPointerType()) {
  1449. // Cannot cast direct function pointers.
  1450. // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
  1451. // T is the ultimate pointee of source and target type.
  1452. if (!CStyle)
  1453. msg = diag::err_bad_const_cast_dest;
  1454. return TC_NotApplicable;
  1455. }
  1456. SrcType = Self.Context.getCanonicalType(SrcType);
  1457. // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
  1458. // completely equal.
  1459. // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
  1460. // in multi-level pointers may change, but the level count must be the same,
  1461. // as must be the final pointee type.
  1462. while (SrcType != DestType &&
  1463. Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
  1464. Qualifiers SrcQuals, DestQuals;
  1465. SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
  1466. DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
  1467. // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
  1468. // the other qualifiers (e.g., address spaces) are identical.
  1469. SrcQuals.removeCVRQualifiers();
  1470. DestQuals.removeCVRQualifiers();
  1471. if (SrcQuals != DestQuals)
  1472. return TC_NotApplicable;
  1473. }
  1474. // Since we're dealing in canonical types, the remainder must be the same.
  1475. if (SrcType != DestType)
  1476. return TC_NotApplicable;
  1477. if (NeedToMaterializeTemporary)
  1478. // This is a const_cast from a class prvalue to an rvalue reference type.
  1479. // Materialize a temporary to store the result of the conversion.
  1480. SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
  1481. SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
  1482. return TC_Success;
  1483. }
  1484. // Checks for undefined behavior in reinterpret_cast.
  1485. // The cases that is checked for is:
  1486. // *reinterpret_cast<T*>(&a)
  1487. // reinterpret_cast<T&>(a)
  1488. // where accessing 'a' as type 'T' will result in undefined behavior.
  1489. void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
  1490. bool IsDereference,
  1491. SourceRange Range) {
  1492. unsigned DiagID = IsDereference ?
  1493. diag::warn_pointer_indirection_from_incompatible_type :
  1494. diag::warn_undefined_reinterpret_cast;
  1495. if (Diags.isIgnored(DiagID, Range.getBegin()))
  1496. return;
  1497. QualType SrcTy, DestTy;
  1498. if (IsDereference) {
  1499. if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
  1500. return;
  1501. }
  1502. SrcTy = SrcType->getPointeeType();
  1503. DestTy = DestType->getPointeeType();
  1504. } else {
  1505. if (!DestType->getAs<ReferenceType>()) {
  1506. return;
  1507. }
  1508. SrcTy = SrcType;
  1509. DestTy = DestType->getPointeeType();
  1510. }
  1511. // Cast is compatible if the types are the same.
  1512. if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
  1513. return;
  1514. }
  1515. // or one of the types is a char or void type
  1516. if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
  1517. SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
  1518. return;
  1519. }
  1520. // or one of the types is a tag type.
  1521. if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
  1522. return;
  1523. }
  1524. // FIXME: Scoped enums?
  1525. if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
  1526. (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
  1527. if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
  1528. return;
  1529. }
  1530. }
  1531. Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
  1532. }
  1533. static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
  1534. QualType DestType) {
  1535. QualType SrcType = SrcExpr.get()->getType();
  1536. if (Self.Context.hasSameType(SrcType, DestType))
  1537. return;
  1538. if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
  1539. if (SrcPtrTy->isObjCSelType()) {
  1540. QualType DT = DestType;
  1541. if (isa<PointerType>(DestType))
  1542. DT = DestType->getPointeeType();
  1543. if (!DT.getUnqualifiedType()->isVoidType())
  1544. Self.Diag(SrcExpr.get()->getExprLoc(),
  1545. diag::warn_cast_pointer_from_sel)
  1546. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  1547. }
  1548. }
  1549. static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
  1550. const Expr *SrcExpr, QualType DestType,
  1551. Sema &Self) {
  1552. QualType SrcType = SrcExpr->getType();
  1553. // Not warning on reinterpret_cast, boolean, constant expressions, etc
  1554. // are not explicit design choices, but consistent with GCC's behavior.
  1555. // Feel free to modify them if you've reason/evidence for an alternative.
  1556. if (CStyle && SrcType->isIntegralType(Self.Context)
  1557. && !SrcType->isBooleanType()
  1558. && !SrcType->isEnumeralType()
  1559. && !SrcExpr->isIntegerConstantExpr(Self.Context)
  1560. && Self.Context.getTypeSize(DestType) >
  1561. Self.Context.getTypeSize(SrcType)) {
  1562. // Separate between casts to void* and non-void* pointers.
  1563. // Some APIs use (abuse) void* for something like a user context,
  1564. // and often that value is an integer even if it isn't a pointer itself.
  1565. // Having a separate warning flag allows users to control the warning
  1566. // for their workflow.
  1567. unsigned Diag = DestType->isVoidPointerType() ?
  1568. diag::warn_int_to_void_pointer_cast
  1569. : diag::warn_int_to_pointer_cast;
  1570. Self.Diag(Loc, Diag) << SrcType << DestType;
  1571. }
  1572. }
  1573. static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
  1574. QualType DestType, bool CStyle,
  1575. const SourceRange &OpRange,
  1576. unsigned &msg,
  1577. CastKind &Kind) {
  1578. bool IsLValueCast = false;
  1579. DestType = Self.Context.getCanonicalType(DestType);
  1580. QualType SrcType = SrcExpr.get()->getType();
  1581. // Is the source an overloaded name? (i.e. &foo)
  1582. // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
  1583. if (SrcType == Self.Context.OverloadTy) {
  1584. // ... unless foo<int> resolves to an lvalue unambiguously.
  1585. // TODO: what if this fails because of DiagnoseUseOfDecl or something
  1586. // like it?
  1587. ExprResult SingleFunctionExpr = SrcExpr;
  1588. if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  1589. SingleFunctionExpr,
  1590. Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
  1591. ) && SingleFunctionExpr.isUsable()) {
  1592. SrcExpr = SingleFunctionExpr;
  1593. SrcType = SrcExpr.get()->getType();
  1594. } else {
  1595. return TC_NotApplicable;
  1596. }
  1597. }
  1598. if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
  1599. if (!SrcExpr.get()->isGLValue()) {
  1600. // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
  1601. // similar comment in const_cast.
  1602. msg = diag::err_bad_cxx_cast_rvalue;
  1603. return TC_NotApplicable;
  1604. }
  1605. if (!CStyle) {
  1606. Self.CheckCompatibleReinterpretCast(SrcType, DestType,
  1607. /*isDereference=*/false, OpRange);
  1608. }
  1609. // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
  1610. // same effect as the conversion *reinterpret_cast<T*>(&x) with the
  1611. // built-in & and * operators.
  1612. const char *inappropriate = nullptr;
  1613. switch (SrcExpr.get()->getObjectKind()) {
  1614. case OK_Ordinary:
  1615. break;
  1616. case OK_BitField: inappropriate = "bit-field"; break;
  1617. case OK_VectorComponent: inappropriate = "vector element"; break;
  1618. case OK_ObjCProperty: inappropriate = "property expression"; break;
  1619. case OK_ObjCSubscript: inappropriate = "container subscripting expression";
  1620. break;
  1621. }
  1622. if (inappropriate) {
  1623. Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
  1624. << inappropriate << DestType
  1625. << OpRange << SrcExpr.get()->getSourceRange();
  1626. msg = 0; SrcExpr = ExprError();
  1627. return TC_NotApplicable;
  1628. }
  1629. // This code does this transformation for the checked types.
  1630. DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
  1631. SrcType = Self.Context.getPointerType(SrcType);
  1632. IsLValueCast = true;
  1633. }
  1634. // Canonicalize source for comparison.
  1635. SrcType = Self.Context.getCanonicalType(SrcType);
  1636. const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
  1637. *SrcMemPtr = SrcType->getAs<MemberPointerType>();
  1638. if (DestMemPtr && SrcMemPtr) {
  1639. // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
  1640. // can be explicitly converted to an rvalue of type "pointer to member
  1641. // of Y of type T2" if T1 and T2 are both function types or both object
  1642. // types.
  1643. if (DestMemPtr->isMemberFunctionPointer() !=
  1644. SrcMemPtr->isMemberFunctionPointer())
  1645. return TC_NotApplicable;
  1646. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
  1647. // constness.
  1648. // A reinterpret_cast followed by a const_cast can, though, so in C-style,
  1649. // we accept it.
  1650. if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  1651. /*CheckObjCLifetime=*/CStyle)) {
  1652. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1653. return TC_Failed;
  1654. }
  1655. if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1656. // We need to determine the inheritance model that the class will use if
  1657. // haven't yet.
  1658. Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
  1659. Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
  1660. }
  1661. // Don't allow casting between member pointers of different sizes.
  1662. if (Self.Context.getTypeSize(DestMemPtr) !=
  1663. Self.Context.getTypeSize(SrcMemPtr)) {
  1664. msg = diag::err_bad_cxx_cast_member_pointer_size;
  1665. return TC_Failed;
  1666. }
  1667. // A valid member pointer cast.
  1668. assert(!IsLValueCast);
  1669. Kind = CK_ReinterpretMemberPointer;
  1670. return TC_Success;
  1671. }
  1672. // See below for the enumeral issue.
  1673. if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
  1674. // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
  1675. // type large enough to hold it. A value of std::nullptr_t can be
  1676. // converted to an integral type; the conversion has the same meaning
  1677. // and validity as a conversion of (void*)0 to the integral type.
  1678. if (Self.Context.getTypeSize(SrcType) >
  1679. Self.Context.getTypeSize(DestType)) {
  1680. msg = diag::err_bad_reinterpret_cast_small_int;
  1681. return TC_Failed;
  1682. }
  1683. Kind = CK_PointerToIntegral;
  1684. return TC_Success;
  1685. }
  1686. bool destIsVector = DestType->isVectorType();
  1687. bool srcIsVector = SrcType->isVectorType();
  1688. if (srcIsVector || destIsVector) {
  1689. // FIXME: Should this also apply to floating point types?
  1690. bool srcIsScalar = SrcType->isIntegralType(Self.Context);
  1691. bool destIsScalar = DestType->isIntegralType(Self.Context);
  1692. // Check if this is a cast between a vector and something else.
  1693. if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
  1694. !(srcIsVector && destIsVector))
  1695. return TC_NotApplicable;
  1696. // If both types have the same size, we can successfully cast.
  1697. if (Self.Context.getTypeSize(SrcType)
  1698. == Self.Context.getTypeSize(DestType)) {
  1699. Kind = CK_BitCast;
  1700. return TC_Success;
  1701. }
  1702. if (destIsScalar)
  1703. msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
  1704. else if (srcIsScalar)
  1705. msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
  1706. else
  1707. msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
  1708. return TC_Failed;
  1709. }
  1710. if (SrcType == DestType) {
  1711. // C++ 5.2.10p2 has a note that mentions that, subject to all other
  1712. // restrictions, a cast to the same type is allowed so long as it does not
  1713. // cast away constness. In C++98, the intent was not entirely clear here,
  1714. // since all other paragraphs explicitly forbid casts to the same type.
  1715. // C++11 clarifies this case with p2.
  1716. //
  1717. // The only allowed types are: integral, enumeration, pointer, or
  1718. // pointer-to-member types. We also won't restrict Obj-C pointers either.
  1719. Kind = CK_NoOp;
  1720. TryCastResult Result = TC_NotApplicable;
  1721. if (SrcType->isIntegralOrEnumerationType() ||
  1722. SrcType->isAnyPointerType() ||
  1723. SrcType->isMemberPointerType() ||
  1724. SrcType->isBlockPointerType()) {
  1725. Result = TC_Success;
  1726. }
  1727. return Result;
  1728. }
  1729. bool destIsPtr = DestType->isAnyPointerType() ||
  1730. DestType->isBlockPointerType();
  1731. bool srcIsPtr = SrcType->isAnyPointerType() ||
  1732. SrcType->isBlockPointerType();
  1733. if (!destIsPtr && !srcIsPtr) {
  1734. // Except for std::nullptr_t->integer and lvalue->reference, which are
  1735. // handled above, at least one of the two arguments must be a pointer.
  1736. return TC_NotApplicable;
  1737. }
  1738. if (DestType->isIntegralType(Self.Context)) {
  1739. assert(srcIsPtr && "One type must be a pointer");
  1740. // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
  1741. // type large enough to hold it; except in Microsoft mode, where the
  1742. // integral type size doesn't matter (except we don't allow bool).
  1743. bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
  1744. !DestType->isBooleanType();
  1745. if ((Self.Context.getTypeSize(SrcType) >
  1746. Self.Context.getTypeSize(DestType)) &&
  1747. !MicrosoftException) {
  1748. msg = diag::err_bad_reinterpret_cast_small_int;
  1749. return TC_Failed;
  1750. }
  1751. Kind = CK_PointerToIntegral;
  1752. return TC_Success;
  1753. }
  1754. if (SrcType->isIntegralOrEnumerationType()) {
  1755. assert(destIsPtr && "One type must be a pointer");
  1756. checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
  1757. Self);
  1758. // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
  1759. // converted to a pointer.
  1760. // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
  1761. // necessarily converted to a null pointer value.]
  1762. Kind = CK_IntegralToPointer;
  1763. return TC_Success;
  1764. }
  1765. if (!destIsPtr || !srcIsPtr) {
  1766. // With the valid non-pointer conversions out of the way, we can be even
  1767. // more stringent.
  1768. return TC_NotApplicable;
  1769. }
  1770. // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
  1771. // The C-style cast operator can.
  1772. if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
  1773. /*CheckObjCLifetime=*/CStyle)) {
  1774. msg = diag::err_bad_cxx_cast_qualifiers_away;
  1775. return TC_Failed;
  1776. }
  1777. // Cannot convert between block pointers and Objective-C object pointers.
  1778. if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
  1779. (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
  1780. return TC_NotApplicable;
  1781. if (IsLValueCast) {
  1782. Kind = CK_LValueBitCast;
  1783. } else if (DestType->isObjCObjectPointerType()) {
  1784. Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
  1785. } else if (DestType->isBlockPointerType()) {
  1786. if (!SrcType->isBlockPointerType()) {
  1787. Kind = CK_AnyPointerToBlockPointerCast;
  1788. } else {
  1789. Kind = CK_BitCast;
  1790. }
  1791. } else {
  1792. Kind = CK_BitCast;
  1793. }
  1794. // Any pointer can be cast to an Objective-C pointer type with a C-style
  1795. // cast.
  1796. if (CStyle && DestType->isObjCObjectPointerType()) {
  1797. return TC_Success;
  1798. }
  1799. if (CStyle)
  1800. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  1801. // Not casting away constness, so the only remaining check is for compatible
  1802. // pointer categories.
  1803. if (SrcType->isFunctionPointerType()) {
  1804. if (DestType->isFunctionPointerType()) {
  1805. // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
  1806. // a pointer to a function of a different type.
  1807. return TC_Success;
  1808. }
  1809. // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
  1810. // an object type or vice versa is conditionally-supported.
  1811. // Compilers support it in C++03 too, though, because it's necessary for
  1812. // casting the return value of dlsym() and GetProcAddress().
  1813. // FIXME: Conditionally-supported behavior should be configurable in the
  1814. // TargetInfo or similar.
  1815. Self.Diag(OpRange.getBegin(),
  1816. Self.getLangOpts().CPlusPlus11 ?
  1817. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  1818. << OpRange;
  1819. return TC_Success;
  1820. }
  1821. if (DestType->isFunctionPointerType()) {
  1822. // See above.
  1823. Self.Diag(OpRange.getBegin(),
  1824. Self.getLangOpts().CPlusPlus11 ?
  1825. diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
  1826. << OpRange;
  1827. return TC_Success;
  1828. }
  1829. // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
  1830. // a pointer to an object of different type.
  1831. // Void pointers are not specified, but supported by every compiler out there.
  1832. // So we finish by allowing everything that remains - it's got to be two
  1833. // object pointers.
  1834. return TC_Success;
  1835. }
  1836. void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
  1837. bool ListInitialization) {
  1838. // Handle placeholders.
  1839. if (isPlaceholder()) {
  1840. // C-style casts can resolve __unknown_any types.
  1841. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  1842. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  1843. SrcExpr.get(), Kind,
  1844. ValueKind, BasePath);
  1845. return;
  1846. }
  1847. checkNonOverloadPlaceholders();
  1848. if (SrcExpr.isInvalid())
  1849. return;
  1850. }
  1851. // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
  1852. // This test is outside everything else because it's the only case where
  1853. // a non-lvalue-reference target type does not lead to decay.
  1854. if (DestType->isVoidType()) {
  1855. Kind = CK_ToVoid;
  1856. if (claimPlaceholder(BuiltinType::Overload)) {
  1857. Self.ResolveAndFixSingleFunctionTemplateSpecialization(
  1858. SrcExpr, /* Decay Function to ptr */ false,
  1859. /* Complain */ true, DestRange, DestType,
  1860. diag::err_bad_cstyle_cast_overload);
  1861. if (SrcExpr.isInvalid())
  1862. return;
  1863. }
  1864. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  1865. return;
  1866. }
  1867. // If the type is dependent, we won't do any other semantic analysis now.
  1868. if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
  1869. SrcExpr.get()->isValueDependent()) {
  1870. assert(Kind == CK_Dependent);
  1871. return;
  1872. }
  1873. // HLSL Change Starts
  1874. // Check for HLSL vector/matrix/array/struct shrinking.
  1875. if (ValueKind == VK_RValue &&
  1876. !FunctionalStyle &&
  1877. !isPlaceholder(BuiltinType::Overload) &&
  1878. Self.getLangOpts().HLSL &&
  1879. SrcExpr.get()->isLValue() &&
  1880. // Cannot use casts on basic type l-values
  1881. !SrcExpr.get()->getType().getCanonicalType()->isBuiltinType() &&
  1882. hlsl::IsConversionToLessOrEqualElements(&Self, SrcExpr, DestType, true)) {
  1883. ValueKind = VK_LValue;
  1884. }
  1885. // HLSL Change Ends
  1886. if (ValueKind == VK_RValue && !DestType->isRecordType() &&
  1887. !isPlaceholder(BuiltinType::Overload)) {
  1888. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  1889. if (SrcExpr.isInvalid())
  1890. return;
  1891. }
  1892. // AltiVec vector initialization with a single literal.
  1893. if (const VectorType *vecTy = DestType->getAs<VectorType>())
  1894. if (vecTy->getVectorKind() == VectorType::AltiVecVector
  1895. && (SrcExpr.get()->getType()->isIntegerType()
  1896. || SrcExpr.get()->getType()->isFloatingType())) {
  1897. Kind = CK_VectorSplat;
  1898. return;
  1899. }
  1900. // C++ [expr.cast]p5: The conversions performed by
  1901. // - a const_cast,
  1902. // - a static_cast,
  1903. // - a static_cast followed by a const_cast,
  1904. // - a reinterpret_cast, or
  1905. // - a reinterpret_cast followed by a const_cast,
  1906. // can be performed using the cast notation of explicit type conversion.
  1907. // [...] If a conversion can be interpreted in more than one of the ways
  1908. // listed above, the interpretation that appears first in the list is used,
  1909. // even if a cast resulting from that interpretation is ill-formed.
  1910. // In plain language, this means trying a const_cast ...
  1911. unsigned msg = diag::err_bad_cxx_cast_generic;
  1912. TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
  1913. /*CStyle*/true, msg);
  1914. if (SrcExpr.isInvalid())
  1915. return;
  1916. if (tcr == TC_Success)
  1917. Kind = CK_NoOp;
  1918. Sema::CheckedConversionKind CCK
  1919. = FunctionalStyle? Sema::CCK_FunctionalCast
  1920. : Sema::CCK_CStyleCast;
  1921. if (tcr == TC_NotApplicable) {
  1922. // ... or if that is not possible, a static_cast, ignoring const, ...
  1923. tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
  1924. msg, Kind, BasePath, ListInitialization);
  1925. if (SrcExpr.isInvalid())
  1926. return;
  1927. if (tcr == TC_NotApplicable) {
  1928. // ... and finally a reinterpret_cast, ignoring const.
  1929. tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
  1930. OpRange, msg, Kind);
  1931. if (SrcExpr.isInvalid())
  1932. return;
  1933. }
  1934. }
  1935. if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
  1936. checkObjCARCConversion(CCK);
  1937. if (tcr != TC_Success && msg != 0) {
  1938. if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
  1939. DeclAccessPair Found;
  1940. FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
  1941. DestType,
  1942. /*Complain*/ true,
  1943. Found);
  1944. if (Fn) {
  1945. // If DestType is a function type (not to be confused with the function
  1946. // pointer type), it will be possible to resolve the function address,
  1947. // but the type cast should be considered as failure.
  1948. OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
  1949. Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
  1950. << OE->getName() << DestType << OpRange
  1951. << OE->getQualifierLoc().getSourceRange();
  1952. Self.NoteAllOverloadCandidates(SrcExpr.get());
  1953. }
  1954. } else {
  1955. diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
  1956. OpRange, SrcExpr.get(), DestType, ListInitialization);
  1957. }
  1958. } else if (Kind == CK_BitCast) {
  1959. checkCastAlign();
  1960. }
  1961. // Clear out SrcExpr if there was a fatal error.
  1962. if (tcr != TC_Success)
  1963. SrcExpr = ExprError();
  1964. }
  1965. /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
  1966. /// non-matching type. Such as enum function call to int, int call to
  1967. /// pointer; etc. Cast to 'void' is an exception.
  1968. static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
  1969. QualType DestType) {
  1970. if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
  1971. SrcExpr.get()->getExprLoc()))
  1972. return;
  1973. if (!isa<CallExpr>(SrcExpr.get()))
  1974. return;
  1975. QualType SrcType = SrcExpr.get()->getType();
  1976. if (DestType.getUnqualifiedType()->isVoidType())
  1977. return;
  1978. if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
  1979. && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
  1980. return;
  1981. if (SrcType->isIntegerType() && DestType->isIntegerType() &&
  1982. (SrcType->isBooleanType() == DestType->isBooleanType()) &&
  1983. (SrcType->isEnumeralType() == DestType->isEnumeralType()))
  1984. return;
  1985. if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
  1986. return;
  1987. if (SrcType->isEnumeralType() && DestType->isEnumeralType())
  1988. return;
  1989. if (SrcType->isComplexType() && DestType->isComplexType())
  1990. return;
  1991. if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
  1992. return;
  1993. Self.Diag(SrcExpr.get()->getExprLoc(),
  1994. diag::warn_bad_function_cast)
  1995. << SrcType << DestType << SrcExpr.get()->getSourceRange();
  1996. }
  1997. /// Check the semantics of a C-style cast operation, in C.
  1998. void CastOperation::CheckCStyleCast() {
  1999. assert(!Self.getLangOpts().CPlusPlus);
  2000. // C-style casts can resolve __unknown_any types.
  2001. if (claimPlaceholder(BuiltinType::UnknownAny)) {
  2002. SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
  2003. SrcExpr.get(), Kind,
  2004. ValueKind, BasePath);
  2005. return;
  2006. }
  2007. // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
  2008. // type needs to be scalar.
  2009. if (DestType->isVoidType()) {
  2010. // We don't necessarily do lvalue-to-rvalue conversions on this.
  2011. SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
  2012. if (SrcExpr.isInvalid())
  2013. return;
  2014. // Cast to void allows any expr type.
  2015. Kind = CK_ToVoid;
  2016. return;
  2017. }
  2018. SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
  2019. if (SrcExpr.isInvalid())
  2020. return;
  2021. QualType SrcType = SrcExpr.get()->getType();
  2022. assert(!SrcType->isPlaceholderType());
  2023. // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
  2024. // address space B is illegal.
  2025. if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
  2026. SrcType->isPointerType()) {
  2027. const PointerType *DestPtr = DestType->getAs<PointerType>();
  2028. if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
  2029. Self.Diag(OpRange.getBegin(),
  2030. diag::err_typecheck_incompatible_address_space)
  2031. << SrcType << DestType << Sema::AA_Casting
  2032. << SrcExpr.get()->getSourceRange();
  2033. SrcExpr = ExprError();
  2034. return;
  2035. }
  2036. }
  2037. if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
  2038. diag::err_typecheck_cast_to_incomplete)) {
  2039. SrcExpr = ExprError();
  2040. return;
  2041. }
  2042. if (!DestType->isScalarType() && !DestType->isVectorType()) {
  2043. const RecordType *DestRecordTy = DestType->getAs<RecordType>();
  2044. if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
  2045. // GCC struct/union extension: allow cast to self.
  2046. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
  2047. << DestType << SrcExpr.get()->getSourceRange();
  2048. Kind = CK_NoOp;
  2049. return;
  2050. }
  2051. // GCC's cast to union extension.
  2052. if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
  2053. RecordDecl *RD = DestRecordTy->getDecl();
  2054. RecordDecl::field_iterator Field, FieldEnd;
  2055. for (Field = RD->field_begin(), FieldEnd = RD->field_end();
  2056. Field != FieldEnd; ++Field) {
  2057. if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
  2058. !Field->isUnnamedBitfield()) {
  2059. Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
  2060. << SrcExpr.get()->getSourceRange();
  2061. break;
  2062. }
  2063. }
  2064. if (Field == FieldEnd) {
  2065. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
  2066. << SrcType << SrcExpr.get()->getSourceRange();
  2067. SrcExpr = ExprError();
  2068. return;
  2069. }
  2070. Kind = CK_ToUnion;
  2071. return;
  2072. }
  2073. // Reject any other conversions to non-scalar types.
  2074. Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
  2075. << DestType << SrcExpr.get()->getSourceRange();
  2076. SrcExpr = ExprError();
  2077. return;
  2078. }
  2079. // The type we're casting to is known to be a scalar or vector.
  2080. // Require the operand to be a scalar or vector.
  2081. if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
  2082. Self.Diag(SrcExpr.get()->getExprLoc(),
  2083. diag::err_typecheck_expect_scalar_operand)
  2084. << SrcType << SrcExpr.get()->getSourceRange();
  2085. SrcExpr = ExprError();
  2086. return;
  2087. }
  2088. if (DestType->isExtVectorType()) {
  2089. SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
  2090. return;
  2091. }
  2092. if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
  2093. if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
  2094. (SrcType->isIntegerType() || SrcType->isFloatingType())) {
  2095. Kind = CK_VectorSplat;
  2096. } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
  2097. SrcExpr = ExprError();
  2098. }
  2099. return;
  2100. }
  2101. if (SrcType->isVectorType()) {
  2102. if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
  2103. SrcExpr = ExprError();
  2104. return;
  2105. }
  2106. // The source and target types are both scalars, i.e.
  2107. // - arithmetic types (fundamental, enum, and complex)
  2108. // - all kinds of pointers
  2109. // Note that member pointers were filtered out with C++, above.
  2110. if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
  2111. Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
  2112. SrcExpr = ExprError();
  2113. return;
  2114. }
  2115. // If either type is a pointer, the other type has to be either an
  2116. // integer or a pointer.
  2117. if (!DestType->isArithmeticType()) {
  2118. if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
  2119. Self.Diag(SrcExpr.get()->getExprLoc(),
  2120. diag::err_cast_pointer_from_non_pointer_int)
  2121. << SrcType << SrcExpr.get()->getSourceRange();
  2122. SrcExpr = ExprError();
  2123. return;
  2124. }
  2125. checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
  2126. DestType, Self);
  2127. } else if (!SrcType->isArithmeticType()) {
  2128. if (!DestType->isIntegralType(Self.Context) &&
  2129. DestType->isArithmeticType()) {
  2130. Self.Diag(SrcExpr.get()->getLocStart(),
  2131. diag::err_cast_pointer_to_non_pointer_int)
  2132. << DestType << SrcExpr.get()->getSourceRange();
  2133. SrcExpr = ExprError();
  2134. return;
  2135. }
  2136. }
  2137. if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
  2138. if (DestType->isHalfType()) {
  2139. Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
  2140. << DestType << SrcExpr.get()->getSourceRange();
  2141. SrcExpr = ExprError();
  2142. return;
  2143. }
  2144. }
  2145. // ARC imposes extra restrictions on casts.
  2146. if (Self.getLangOpts().ObjCAutoRefCount) {
  2147. checkObjCARCConversion(Sema::CCK_CStyleCast);
  2148. if (SrcExpr.isInvalid())
  2149. return;
  2150. if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
  2151. if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
  2152. Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
  2153. Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
  2154. if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
  2155. ExprPtr->getPointeeType()->isObjCLifetimeType() &&
  2156. !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
  2157. Self.Diag(SrcExpr.get()->getLocStart(),
  2158. diag::err_typecheck_incompatible_ownership)
  2159. << SrcType << DestType << Sema::AA_Casting
  2160. << SrcExpr.get()->getSourceRange();
  2161. return;
  2162. }
  2163. }
  2164. }
  2165. else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
  2166. Self.Diag(SrcExpr.get()->getLocStart(),
  2167. diag::err_arc_convesion_of_weak_unavailable)
  2168. << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
  2169. SrcExpr = ExprError();
  2170. return;
  2171. }
  2172. }
  2173. DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
  2174. DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
  2175. Kind = Self.PrepareScalarCast(SrcExpr, DestType);
  2176. if (SrcExpr.isInvalid())
  2177. return;
  2178. if (Kind == CK_BitCast)
  2179. checkCastAlign();
  2180. // -Wcast-qual
  2181. QualType TheOffendingSrcType, TheOffendingDestType;
  2182. Qualifiers CastAwayQualifiers;
  2183. if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
  2184. CastsAwayConstness(Self, SrcType, DestType, true, false,
  2185. &TheOffendingSrcType, &TheOffendingDestType,
  2186. &CastAwayQualifiers)) {
  2187. int qualifiers = -1;
  2188. if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
  2189. qualifiers = 0;
  2190. } else if (CastAwayQualifiers.hasConst()) {
  2191. qualifiers = 1;
  2192. } else if (CastAwayQualifiers.hasVolatile()) {
  2193. qualifiers = 2;
  2194. }
  2195. // This is a variant of int **x; const int **y = (const int **)x;
  2196. if (qualifiers == -1)
  2197. Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
  2198. SrcType << DestType;
  2199. else
  2200. Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
  2201. TheOffendingSrcType << TheOffendingDestType << qualifiers;
  2202. }
  2203. }
  2204. ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
  2205. TypeSourceInfo *CastTypeInfo,
  2206. SourceLocation RPLoc,
  2207. Expr *CastExpr) {
  2208. CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
  2209. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2210. Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
  2211. if (getLangOpts().CPlusPlus) {
  2212. Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
  2213. isa<InitListExpr>(CastExpr));
  2214. } else {
  2215. Op.CheckCStyleCast();
  2216. }
  2217. if (Op.SrcExpr.isInvalid())
  2218. return ExprError();
  2219. return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
  2220. Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
  2221. &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
  2222. }
  2223. ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
  2224. SourceLocation LPLoc,
  2225. Expr *CastExpr,
  2226. SourceLocation RPLoc) {
  2227. assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
  2228. CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
  2229. Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
  2230. Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
  2231. Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
  2232. if (Op.SrcExpr.isInvalid())
  2233. return ExprError();
  2234. if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
  2235. ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
  2236. return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
  2237. Op.ValueKind, CastTypeInfo, Op.Kind,
  2238. Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
  2239. }