CGClass.cpp 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047
  1. //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code dealing with C++ code generation of classes
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGBlocks.h"
  13. #include "CGCXXABI.h"
  14. #include "CGDebugInfo.h"
  15. #include "CGRecordLayout.h"
  16. #include "CodeGenFunction.h"
  17. #include "TargetInfo.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/CXXInheritance.h"
  20. #include "clang/AST/CharUnits.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/RecordLayout.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/Basic/CodeGenOptions.h"
  26. #include "clang/Basic/TargetBuiltins.h"
  27. #include "clang/CodeGen/CGFunctionInfo.h"
  28. #include "llvm/IR/Intrinsics.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/Transforms/Utils/SanitizerStats.h"
  31. #include <optional>
  32. using namespace clang;
  33. using namespace CodeGen;
  34. /// Return the best known alignment for an unknown pointer to a
  35. /// particular class.
  36. CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) {
  37. if (!RD->hasDefinition())
  38. return CharUnits::One(); // Hopefully won't be used anywhere.
  39. auto &layout = getContext().getASTRecordLayout(RD);
  40. // If the class is final, then we know that the pointer points to an
  41. // object of that type and can use the full alignment.
  42. if (RD->isEffectivelyFinal())
  43. return layout.getAlignment();
  44. // Otherwise, we have to assume it could be a subclass.
  45. return layout.getNonVirtualAlignment();
  46. }
  47. /// Return the smallest possible amount of storage that might be allocated
  48. /// starting from the beginning of an object of a particular class.
  49. ///
  50. /// This may be smaller than sizeof(RD) if RD has virtual base classes.
  51. CharUnits CodeGenModule::getMinimumClassObjectSize(const CXXRecordDecl *RD) {
  52. if (!RD->hasDefinition())
  53. return CharUnits::One();
  54. auto &layout = getContext().getASTRecordLayout(RD);
  55. // If the class is final, then we know that the pointer points to an
  56. // object of that type and can use the full alignment.
  57. if (RD->isEffectivelyFinal())
  58. return layout.getSize();
  59. // Otherwise, we have to assume it could be a subclass.
  60. return std::max(layout.getNonVirtualSize(), CharUnits::One());
  61. }
  62. /// Return the best known alignment for a pointer to a virtual base,
  63. /// given the alignment of a pointer to the derived class.
  64. CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign,
  65. const CXXRecordDecl *derivedClass,
  66. const CXXRecordDecl *vbaseClass) {
  67. // The basic idea here is that an underaligned derived pointer might
  68. // indicate an underaligned base pointer.
  69. assert(vbaseClass->isCompleteDefinition());
  70. auto &baseLayout = getContext().getASTRecordLayout(vbaseClass);
  71. CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment();
  72. return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass,
  73. expectedVBaseAlign);
  74. }
  75. CharUnits
  76. CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign,
  77. const CXXRecordDecl *baseDecl,
  78. CharUnits expectedTargetAlign) {
  79. // If the base is an incomplete type (which is, alas, possible with
  80. // member pointers), be pessimistic.
  81. if (!baseDecl->isCompleteDefinition())
  82. return std::min(actualBaseAlign, expectedTargetAlign);
  83. auto &baseLayout = getContext().getASTRecordLayout(baseDecl);
  84. CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment();
  85. // If the class is properly aligned, assume the target offset is, too.
  86. //
  87. // This actually isn't necessarily the right thing to do --- if the
  88. // class is a complete object, but it's only properly aligned for a
  89. // base subobject, then the alignments of things relative to it are
  90. // probably off as well. (Note that this requires the alignment of
  91. // the target to be greater than the NV alignment of the derived
  92. // class.)
  93. //
  94. // However, our approach to this kind of under-alignment can only
  95. // ever be best effort; after all, we're never going to propagate
  96. // alignments through variables or parameters. Note, in particular,
  97. // that constructing a polymorphic type in an address that's less
  98. // than pointer-aligned will generally trap in the constructor,
  99. // unless we someday add some sort of attribute to change the
  100. // assumed alignment of 'this'. So our goal here is pretty much
  101. // just to allow the user to explicitly say that a pointer is
  102. // under-aligned and then safely access its fields and vtables.
  103. if (actualBaseAlign >= expectedBaseAlign) {
  104. return expectedTargetAlign;
  105. }
  106. // Otherwise, we might be offset by an arbitrary multiple of the
  107. // actual alignment. The correct adjustment is to take the min of
  108. // the two alignments.
  109. return std::min(actualBaseAlign, expectedTargetAlign);
  110. }
  111. Address CodeGenFunction::LoadCXXThisAddress() {
  112. assert(CurFuncDecl && "loading 'this' without a func declaration?");
  113. auto *MD = cast<CXXMethodDecl>(CurFuncDecl);
  114. // Lazily compute CXXThisAlignment.
  115. if (CXXThisAlignment.isZero()) {
  116. // Just use the best known alignment for the parent.
  117. // TODO: if we're currently emitting a complete-object ctor/dtor,
  118. // we can always use the complete-object alignment.
  119. CXXThisAlignment = CGM.getClassPointerAlignment(MD->getParent());
  120. }
  121. llvm::Type *Ty = ConvertType(MD->getThisType()->getPointeeType());
  122. return Address(LoadCXXThis(), Ty, CXXThisAlignment);
  123. }
  124. /// Emit the address of a field using a member data pointer.
  125. ///
  126. /// \param E Only used for emergency diagnostics
  127. Address
  128. CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base,
  129. llvm::Value *memberPtr,
  130. const MemberPointerType *memberPtrType,
  131. LValueBaseInfo *BaseInfo,
  132. TBAAAccessInfo *TBAAInfo) {
  133. // Ask the ABI to compute the actual address.
  134. llvm::Value *ptr =
  135. CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base,
  136. memberPtr, memberPtrType);
  137. QualType memberType = memberPtrType->getPointeeType();
  138. CharUnits memberAlign =
  139. CGM.getNaturalTypeAlignment(memberType, BaseInfo, TBAAInfo);
  140. memberAlign =
  141. CGM.getDynamicOffsetAlignment(base.getAlignment(),
  142. memberPtrType->getClass()->getAsCXXRecordDecl(),
  143. memberAlign);
  144. return Address(ptr, ConvertTypeForMem(memberPtrType->getPointeeType()),
  145. memberAlign);
  146. }
  147. CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
  148. const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
  149. CastExpr::path_const_iterator End) {
  150. CharUnits Offset = CharUnits::Zero();
  151. const ASTContext &Context = getContext();
  152. const CXXRecordDecl *RD = DerivedClass;
  153. for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
  154. const CXXBaseSpecifier *Base = *I;
  155. assert(!Base->isVirtual() && "Should not see virtual bases here!");
  156. // Get the layout.
  157. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  158. const auto *BaseDecl =
  159. cast<CXXRecordDecl>(Base->getType()->castAs<RecordType>()->getDecl());
  160. // Add the offset.
  161. Offset += Layout.getBaseClassOffset(BaseDecl);
  162. RD = BaseDecl;
  163. }
  164. return Offset;
  165. }
  166. llvm::Constant *
  167. CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
  168. CastExpr::path_const_iterator PathBegin,
  169. CastExpr::path_const_iterator PathEnd) {
  170. assert(PathBegin != PathEnd && "Base path should not be empty!");
  171. CharUnits Offset =
  172. computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
  173. if (Offset.isZero())
  174. return nullptr;
  175. llvm::Type *PtrDiffTy =
  176. Types.ConvertType(getContext().getPointerDiffType());
  177. return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
  178. }
  179. /// Gets the address of a direct base class within a complete object.
  180. /// This should only be used for (1) non-virtual bases or (2) virtual bases
  181. /// when the type is known to be complete (e.g. in complete destructors).
  182. ///
  183. /// The object pointed to by 'This' is assumed to be non-null.
  184. Address
  185. CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This,
  186. const CXXRecordDecl *Derived,
  187. const CXXRecordDecl *Base,
  188. bool BaseIsVirtual) {
  189. // 'this' must be a pointer (in some address space) to Derived.
  190. assert(This.getElementType() == ConvertType(Derived));
  191. // Compute the offset of the virtual base.
  192. CharUnits Offset;
  193. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
  194. if (BaseIsVirtual)
  195. Offset = Layout.getVBaseClassOffset(Base);
  196. else
  197. Offset = Layout.getBaseClassOffset(Base);
  198. // Shift and cast down to the base type.
  199. // TODO: for complete types, this should be possible with a GEP.
  200. Address V = This;
  201. if (!Offset.isZero()) {
  202. V = Builder.CreateElementBitCast(V, Int8Ty);
  203. V = Builder.CreateConstInBoundsByteGEP(V, Offset);
  204. }
  205. V = Builder.CreateElementBitCast(V, ConvertType(Base));
  206. return V;
  207. }
  208. static Address
  209. ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr,
  210. CharUnits nonVirtualOffset,
  211. llvm::Value *virtualOffset,
  212. const CXXRecordDecl *derivedClass,
  213. const CXXRecordDecl *nearestVBase) {
  214. // Assert that we have something to do.
  215. assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
  216. // Compute the offset from the static and dynamic components.
  217. llvm::Value *baseOffset;
  218. if (!nonVirtualOffset.isZero()) {
  219. llvm::Type *OffsetType =
  220. (CGF.CGM.getTarget().getCXXABI().isItaniumFamily() &&
  221. CGF.CGM.getItaniumVTableContext().isRelativeLayout())
  222. ? CGF.Int32Ty
  223. : CGF.PtrDiffTy;
  224. baseOffset =
  225. llvm::ConstantInt::get(OffsetType, nonVirtualOffset.getQuantity());
  226. if (virtualOffset) {
  227. baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
  228. }
  229. } else {
  230. baseOffset = virtualOffset;
  231. }
  232. // Apply the base offset.
  233. llvm::Value *ptr = addr.getPointer();
  234. unsigned AddrSpace = ptr->getType()->getPointerAddressSpace();
  235. ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8Ty->getPointerTo(AddrSpace));
  236. ptr = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, ptr, baseOffset, "add.ptr");
  237. // If we have a virtual component, the alignment of the result will
  238. // be relative only to the known alignment of that vbase.
  239. CharUnits alignment;
  240. if (virtualOffset) {
  241. assert(nearestVBase && "virtual offset without vbase?");
  242. alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(),
  243. derivedClass, nearestVBase);
  244. } else {
  245. alignment = addr.getAlignment();
  246. }
  247. alignment = alignment.alignmentAtOffset(nonVirtualOffset);
  248. return Address(ptr, CGF.Int8Ty, alignment);
  249. }
  250. Address CodeGenFunction::GetAddressOfBaseClass(
  251. Address Value, const CXXRecordDecl *Derived,
  252. CastExpr::path_const_iterator PathBegin,
  253. CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
  254. SourceLocation Loc) {
  255. assert(PathBegin != PathEnd && "Base path should not be empty!");
  256. CastExpr::path_const_iterator Start = PathBegin;
  257. const CXXRecordDecl *VBase = nullptr;
  258. // Sema has done some convenient canonicalization here: if the
  259. // access path involved any virtual steps, the conversion path will
  260. // *start* with a step down to the correct virtual base subobject,
  261. // and hence will not require any further steps.
  262. if ((*Start)->isVirtual()) {
  263. VBase = cast<CXXRecordDecl>(
  264. (*Start)->getType()->castAs<RecordType>()->getDecl());
  265. ++Start;
  266. }
  267. // Compute the static offset of the ultimate destination within its
  268. // allocating subobject (the virtual base, if there is one, or else
  269. // the "complete" object that we see).
  270. CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
  271. VBase ? VBase : Derived, Start, PathEnd);
  272. // If there's a virtual step, we can sometimes "devirtualize" it.
  273. // For now, that's limited to when the derived type is final.
  274. // TODO: "devirtualize" this for accesses to known-complete objects.
  275. if (VBase && Derived->hasAttr<FinalAttr>()) {
  276. const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
  277. CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
  278. NonVirtualOffset += vBaseOffset;
  279. VBase = nullptr; // we no longer have a virtual step
  280. }
  281. // Get the base pointer type.
  282. llvm::Type *BaseValueTy = ConvertType((PathEnd[-1])->getType());
  283. llvm::Type *BasePtrTy =
  284. BaseValueTy->getPointerTo(Value.getType()->getPointerAddressSpace());
  285. QualType DerivedTy = getContext().getRecordType(Derived);
  286. CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived);
  287. // If the static offset is zero and we don't have a virtual step,
  288. // just do a bitcast; null checks are unnecessary.
  289. if (NonVirtualOffset.isZero() && !VBase) {
  290. if (sanitizePerformTypeCheck()) {
  291. SanitizerSet SkippedChecks;
  292. SkippedChecks.set(SanitizerKind::Null, !NullCheckValue);
  293. EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(),
  294. DerivedTy, DerivedAlign, SkippedChecks);
  295. }
  296. return Builder.CreateElementBitCast(Value, BaseValueTy);
  297. }
  298. llvm::BasicBlock *origBB = nullptr;
  299. llvm::BasicBlock *endBB = nullptr;
  300. // Skip over the offset (and the vtable load) if we're supposed to
  301. // null-check the pointer.
  302. if (NullCheckValue) {
  303. origBB = Builder.GetInsertBlock();
  304. llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
  305. endBB = createBasicBlock("cast.end");
  306. llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer());
  307. Builder.CreateCondBr(isNull, endBB, notNullBB);
  308. EmitBlock(notNullBB);
  309. }
  310. if (sanitizePerformTypeCheck()) {
  311. SanitizerSet SkippedChecks;
  312. SkippedChecks.set(SanitizerKind::Null, true);
  313. EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc,
  314. Value.getPointer(), DerivedTy, DerivedAlign, SkippedChecks);
  315. }
  316. // Compute the virtual offset.
  317. llvm::Value *VirtualOffset = nullptr;
  318. if (VBase) {
  319. VirtualOffset =
  320. CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
  321. }
  322. // Apply both offsets.
  323. Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
  324. VirtualOffset, Derived, VBase);
  325. // Cast to the destination type.
  326. Value = Builder.CreateElementBitCast(Value, BaseValueTy);
  327. // Build a phi if we needed a null check.
  328. if (NullCheckValue) {
  329. llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
  330. Builder.CreateBr(endBB);
  331. EmitBlock(endBB);
  332. llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
  333. PHI->addIncoming(Value.getPointer(), notNullBB);
  334. PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
  335. Value = Value.withPointer(PHI);
  336. }
  337. return Value;
  338. }
  339. Address
  340. CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr,
  341. const CXXRecordDecl *Derived,
  342. CastExpr::path_const_iterator PathBegin,
  343. CastExpr::path_const_iterator PathEnd,
  344. bool NullCheckValue) {
  345. assert(PathBegin != PathEnd && "Base path should not be empty!");
  346. QualType DerivedTy =
  347. getContext().getCanonicalType(getContext().getTagDeclType(Derived));
  348. unsigned AddrSpace = BaseAddr.getAddressSpace();
  349. llvm::Type *DerivedValueTy = ConvertType(DerivedTy);
  350. llvm::Type *DerivedPtrTy = DerivedValueTy->getPointerTo(AddrSpace);
  351. llvm::Value *NonVirtualOffset =
  352. CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
  353. if (!NonVirtualOffset) {
  354. // No offset, we can just cast back.
  355. return Builder.CreateElementBitCast(BaseAddr, DerivedValueTy);
  356. }
  357. llvm::BasicBlock *CastNull = nullptr;
  358. llvm::BasicBlock *CastNotNull = nullptr;
  359. llvm::BasicBlock *CastEnd = nullptr;
  360. if (NullCheckValue) {
  361. CastNull = createBasicBlock("cast.null");
  362. CastNotNull = createBasicBlock("cast.notnull");
  363. CastEnd = createBasicBlock("cast.end");
  364. llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer());
  365. Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
  366. EmitBlock(CastNotNull);
  367. }
  368. // Apply the offset.
  369. llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy);
  370. Value = Builder.CreateInBoundsGEP(
  371. Int8Ty, Value, Builder.CreateNeg(NonVirtualOffset), "sub.ptr");
  372. // Just cast.
  373. Value = Builder.CreateBitCast(Value, DerivedPtrTy);
  374. // Produce a PHI if we had a null-check.
  375. if (NullCheckValue) {
  376. Builder.CreateBr(CastEnd);
  377. EmitBlock(CastNull);
  378. Builder.CreateBr(CastEnd);
  379. EmitBlock(CastEnd);
  380. llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
  381. PHI->addIncoming(Value, CastNotNull);
  382. PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
  383. Value = PHI;
  384. }
  385. return Address(Value, DerivedValueTy, CGM.getClassPointerAlignment(Derived));
  386. }
  387. llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
  388. bool ForVirtualBase,
  389. bool Delegating) {
  390. if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
  391. // This constructor/destructor does not need a VTT parameter.
  392. return nullptr;
  393. }
  394. const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
  395. const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
  396. uint64_t SubVTTIndex;
  397. if (Delegating) {
  398. // If this is a delegating constructor call, just load the VTT.
  399. return LoadCXXVTT();
  400. } else if (RD == Base) {
  401. // If the record matches the base, this is the complete ctor/dtor
  402. // variant calling the base variant in a class with virtual bases.
  403. assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
  404. "doing no-op VTT offset in base dtor/ctor?");
  405. assert(!ForVirtualBase && "Can't have same class as virtual base!");
  406. SubVTTIndex = 0;
  407. } else {
  408. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  409. CharUnits BaseOffset = ForVirtualBase ?
  410. Layout.getVBaseClassOffset(Base) :
  411. Layout.getBaseClassOffset(Base);
  412. SubVTTIndex =
  413. CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
  414. assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
  415. }
  416. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  417. // A VTT parameter was passed to the constructor, use it.
  418. llvm::Value *VTT = LoadCXXVTT();
  419. return Builder.CreateConstInBoundsGEP1_64(VoidPtrTy, VTT, SubVTTIndex);
  420. } else {
  421. // We're the complete constructor, so get the VTT by name.
  422. llvm::GlobalValue *VTT = CGM.getVTables().GetAddrOfVTT(RD);
  423. return Builder.CreateConstInBoundsGEP2_64(
  424. VTT->getValueType(), VTT, 0, SubVTTIndex);
  425. }
  426. }
  427. namespace {
  428. /// Call the destructor for a direct base class.
  429. struct CallBaseDtor final : EHScopeStack::Cleanup {
  430. const CXXRecordDecl *BaseClass;
  431. bool BaseIsVirtual;
  432. CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
  433. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  434. void Emit(CodeGenFunction &CGF, Flags flags) override {
  435. const CXXRecordDecl *DerivedClass =
  436. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  437. const CXXDestructorDecl *D = BaseClass->getDestructor();
  438. // We are already inside a destructor, so presumably the object being
  439. // destroyed should have the expected type.
  440. QualType ThisTy = D->getThisObjectType();
  441. Address Addr =
  442. CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(),
  443. DerivedClass, BaseClass,
  444. BaseIsVirtual);
  445. CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
  446. /*Delegating=*/false, Addr, ThisTy);
  447. }
  448. };
  449. /// A visitor which checks whether an initializer uses 'this' in a
  450. /// way which requires the vtable to be properly set.
  451. struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
  452. typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
  453. bool UsesThis;
  454. DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
  455. // Black-list all explicit and implicit references to 'this'.
  456. //
  457. // Do we need to worry about external references to 'this' derived
  458. // from arbitrary code? If so, then anything which runs arbitrary
  459. // external code might potentially access the vtable.
  460. void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
  461. };
  462. } // end anonymous namespace
  463. static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
  464. DynamicThisUseChecker Checker(C);
  465. Checker.Visit(Init);
  466. return Checker.UsesThis;
  467. }
  468. static void EmitBaseInitializer(CodeGenFunction &CGF,
  469. const CXXRecordDecl *ClassDecl,
  470. CXXCtorInitializer *BaseInit) {
  471. assert(BaseInit->isBaseInitializer() &&
  472. "Must have base initializer!");
  473. Address ThisPtr = CGF.LoadCXXThisAddress();
  474. const Type *BaseType = BaseInit->getBaseClass();
  475. const auto *BaseClassDecl =
  476. cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
  477. bool isBaseVirtual = BaseInit->isBaseVirtual();
  478. // If the initializer for the base (other than the constructor
  479. // itself) accesses 'this' in any way, we need to initialize the
  480. // vtables.
  481. if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
  482. CGF.InitializeVTablePointers(ClassDecl);
  483. // We can pretend to be a complete class because it only matters for
  484. // virtual bases, and we only do virtual bases for complete ctors.
  485. Address V =
  486. CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
  487. BaseClassDecl,
  488. isBaseVirtual);
  489. AggValueSlot AggSlot =
  490. AggValueSlot::forAddr(
  491. V, Qualifiers(),
  492. AggValueSlot::IsDestructed,
  493. AggValueSlot::DoesNotNeedGCBarriers,
  494. AggValueSlot::IsNotAliased,
  495. CGF.getOverlapForBaseInit(ClassDecl, BaseClassDecl, isBaseVirtual));
  496. CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
  497. if (CGF.CGM.getLangOpts().Exceptions &&
  498. !BaseClassDecl->hasTrivialDestructor())
  499. CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
  500. isBaseVirtual);
  501. }
  502. static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
  503. auto *CD = dyn_cast<CXXConstructorDecl>(D);
  504. if (!(CD && CD->isCopyOrMoveConstructor()) &&
  505. !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
  506. return false;
  507. // We can emit a memcpy for a trivial copy or move constructor/assignment.
  508. if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
  509. return true;
  510. // We *must* emit a memcpy for a defaulted union copy or move op.
  511. if (D->getParent()->isUnion() && D->isDefaulted())
  512. return true;
  513. return false;
  514. }
  515. static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
  516. CXXCtorInitializer *MemberInit,
  517. LValue &LHS) {
  518. FieldDecl *Field = MemberInit->getAnyMember();
  519. if (MemberInit->isIndirectMemberInitializer()) {
  520. // If we are initializing an anonymous union field, drill down to the field.
  521. IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
  522. for (const auto *I : IndirectField->chain())
  523. LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
  524. } else {
  525. LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
  526. }
  527. }
  528. static void EmitMemberInitializer(CodeGenFunction &CGF,
  529. const CXXRecordDecl *ClassDecl,
  530. CXXCtorInitializer *MemberInit,
  531. const CXXConstructorDecl *Constructor,
  532. FunctionArgList &Args) {
  533. ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
  534. assert(MemberInit->isAnyMemberInitializer() &&
  535. "Must have member initializer!");
  536. assert(MemberInit->getInit() && "Must have initializer!");
  537. // non-static data member initializers.
  538. FieldDecl *Field = MemberInit->getAnyMember();
  539. QualType FieldType = Field->getType();
  540. llvm::Value *ThisPtr = CGF.LoadCXXThis();
  541. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  542. LValue LHS;
  543. // If a base constructor is being emitted, create an LValue that has the
  544. // non-virtual alignment.
  545. if (CGF.CurGD.getCtorType() == Ctor_Base)
  546. LHS = CGF.MakeNaturalAlignPointeeAddrLValue(ThisPtr, RecordTy);
  547. else
  548. LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
  549. EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
  550. // Special case: if we are in a copy or move constructor, and we are copying
  551. // an array of PODs or classes with trivial copy constructors, ignore the
  552. // AST and perform the copy we know is equivalent.
  553. // FIXME: This is hacky at best... if we had a bit more explicit information
  554. // in the AST, we could generalize it more easily.
  555. const ConstantArrayType *Array
  556. = CGF.getContext().getAsConstantArrayType(FieldType);
  557. if (Array && Constructor->isDefaulted() &&
  558. Constructor->isCopyOrMoveConstructor()) {
  559. QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
  560. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  561. if (BaseElementTy.isPODType(CGF.getContext()) ||
  562. (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
  563. unsigned SrcArgIndex =
  564. CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
  565. llvm::Value *SrcPtr
  566. = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
  567. LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  568. LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
  569. // Copy the aggregate.
  570. CGF.EmitAggregateCopy(LHS, Src, FieldType, CGF.getOverlapForFieldInit(Field),
  571. LHS.isVolatileQualified());
  572. // Ensure that we destroy the objects if an exception is thrown later in
  573. // the constructor.
  574. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  575. if (CGF.needsEHCleanup(dtorKind))
  576. CGF.pushEHDestroy(dtorKind, LHS.getAddress(CGF), FieldType);
  577. return;
  578. }
  579. }
  580. CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit());
  581. }
  582. void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS,
  583. Expr *Init) {
  584. QualType FieldType = Field->getType();
  585. switch (getEvaluationKind(FieldType)) {
  586. case TEK_Scalar:
  587. if (LHS.isSimple()) {
  588. EmitExprAsInit(Init, Field, LHS, false);
  589. } else {
  590. RValue RHS = RValue::get(EmitScalarExpr(Init));
  591. EmitStoreThroughLValue(RHS, LHS);
  592. }
  593. break;
  594. case TEK_Complex:
  595. EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
  596. break;
  597. case TEK_Aggregate: {
  598. AggValueSlot Slot = AggValueSlot::forLValue(
  599. LHS, *this, AggValueSlot::IsDestructed,
  600. AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
  601. getOverlapForFieldInit(Field), AggValueSlot::IsNotZeroed,
  602. // Checks are made by the code that calls constructor.
  603. AggValueSlot::IsSanitizerChecked);
  604. EmitAggExpr(Init, Slot);
  605. break;
  606. }
  607. }
  608. // Ensure that we destroy this object if an exception is thrown
  609. // later in the constructor.
  610. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  611. if (needsEHCleanup(dtorKind))
  612. pushEHDestroy(dtorKind, LHS.getAddress(*this), FieldType);
  613. }
  614. /// Checks whether the given constructor is a valid subject for the
  615. /// complete-to-base constructor delegation optimization, i.e.
  616. /// emitting the complete constructor as a simple call to the base
  617. /// constructor.
  618. bool CodeGenFunction::IsConstructorDelegationValid(
  619. const CXXConstructorDecl *Ctor) {
  620. // Currently we disable the optimization for classes with virtual
  621. // bases because (1) the addresses of parameter variables need to be
  622. // consistent across all initializers but (2) the delegate function
  623. // call necessarily creates a second copy of the parameter variable.
  624. //
  625. // The limiting example (purely theoretical AFAIK):
  626. // struct A { A(int &c) { c++; } };
  627. // struct B : virtual A {
  628. // B(int count) : A(count) { printf("%d\n", count); }
  629. // };
  630. // ...although even this example could in principle be emitted as a
  631. // delegation since the address of the parameter doesn't escape.
  632. if (Ctor->getParent()->getNumVBases()) {
  633. // TODO: white-list trivial vbase initializers. This case wouldn't
  634. // be subject to the restrictions below.
  635. // TODO: white-list cases where:
  636. // - there are no non-reference parameters to the constructor
  637. // - the initializers don't access any non-reference parameters
  638. // - the initializers don't take the address of non-reference
  639. // parameters
  640. // - etc.
  641. // If we ever add any of the above cases, remember that:
  642. // - function-try-blocks will always exclude this optimization
  643. // - we need to perform the constructor prologue and cleanup in
  644. // EmitConstructorBody.
  645. return false;
  646. }
  647. // We also disable the optimization for variadic functions because
  648. // it's impossible to "re-pass" varargs.
  649. if (Ctor->getType()->castAs<FunctionProtoType>()->isVariadic())
  650. return false;
  651. // FIXME: Decide if we can do a delegation of a delegating constructor.
  652. if (Ctor->isDelegatingConstructor())
  653. return false;
  654. return true;
  655. }
  656. // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
  657. // to poison the extra field paddings inserted under
  658. // -fsanitize-address-field-padding=1|2.
  659. void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
  660. ASTContext &Context = getContext();
  661. const CXXRecordDecl *ClassDecl =
  662. Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
  663. : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
  664. if (!ClassDecl->mayInsertExtraPadding()) return;
  665. struct SizeAndOffset {
  666. uint64_t Size;
  667. uint64_t Offset;
  668. };
  669. unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
  670. const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
  671. // Populate sizes and offsets of fields.
  672. SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
  673. for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
  674. SSV[i].Offset =
  675. Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
  676. size_t NumFields = 0;
  677. for (const auto *Field : ClassDecl->fields()) {
  678. const FieldDecl *D = Field;
  679. auto FieldInfo = Context.getTypeInfoInChars(D->getType());
  680. CharUnits FieldSize = FieldInfo.Width;
  681. assert(NumFields < SSV.size());
  682. SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
  683. NumFields++;
  684. }
  685. assert(NumFields == SSV.size());
  686. if (SSV.size() <= 1) return;
  687. // We will insert calls to __asan_* run-time functions.
  688. // LLVM AddressSanitizer pass may decide to inline them later.
  689. llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
  690. llvm::FunctionType *FTy =
  691. llvm::FunctionType::get(CGM.VoidTy, Args, false);
  692. llvm::FunctionCallee F = CGM.CreateRuntimeFunction(
  693. FTy, Prologue ? "__asan_poison_intra_object_redzone"
  694. : "__asan_unpoison_intra_object_redzone");
  695. llvm::Value *ThisPtr = LoadCXXThis();
  696. ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
  697. uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
  698. // For each field check if it has sufficient padding,
  699. // if so (un)poison it with a call.
  700. for (size_t i = 0; i < SSV.size(); i++) {
  701. uint64_t AsanAlignment = 8;
  702. uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
  703. uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
  704. uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
  705. if (PoisonSize < AsanAlignment || !SSV[i].Size ||
  706. (NextField % AsanAlignment) != 0)
  707. continue;
  708. Builder.CreateCall(
  709. F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
  710. Builder.getIntN(PtrSize, PoisonSize)});
  711. }
  712. }
  713. /// EmitConstructorBody - Emits the body of the current constructor.
  714. void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
  715. EmitAsanPrologueOrEpilogue(true);
  716. const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
  717. CXXCtorType CtorType = CurGD.getCtorType();
  718. assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
  719. CtorType == Ctor_Complete) &&
  720. "can only generate complete ctor for this ABI");
  721. // Before we go any further, try the complete->base constructor
  722. // delegation optimization.
  723. if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
  724. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  725. EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getEndLoc());
  726. return;
  727. }
  728. const FunctionDecl *Definition = nullptr;
  729. Stmt *Body = Ctor->getBody(Definition);
  730. assert(Definition == Ctor && "emitting wrong constructor body");
  731. // Enter the function-try-block before the constructor prologue if
  732. // applicable.
  733. bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
  734. if (IsTryBody)
  735. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  736. incrementProfileCounter(Body);
  737. RunCleanupsScope RunCleanups(*this);
  738. // TODO: in restricted cases, we can emit the vbase initializers of
  739. // a complete ctor and then delegate to the base ctor.
  740. // Emit the constructor prologue, i.e. the base and member
  741. // initializers.
  742. EmitCtorPrologue(Ctor, CtorType, Args);
  743. // Emit the body of the statement.
  744. if (IsTryBody)
  745. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  746. else if (Body)
  747. EmitStmt(Body);
  748. // Emit any cleanup blocks associated with the member or base
  749. // initializers, which includes (along the exceptional path) the
  750. // destructors for those members and bases that were fully
  751. // constructed.
  752. RunCleanups.ForceCleanup();
  753. if (IsTryBody)
  754. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  755. }
  756. namespace {
  757. /// RAII object to indicate that codegen is copying the value representation
  758. /// instead of the object representation. Useful when copying a struct or
  759. /// class which has uninitialized members and we're only performing
  760. /// lvalue-to-rvalue conversion on the object but not its members.
  761. class CopyingValueRepresentation {
  762. public:
  763. explicit CopyingValueRepresentation(CodeGenFunction &CGF)
  764. : CGF(CGF), OldSanOpts(CGF.SanOpts) {
  765. CGF.SanOpts.set(SanitizerKind::Bool, false);
  766. CGF.SanOpts.set(SanitizerKind::Enum, false);
  767. }
  768. ~CopyingValueRepresentation() {
  769. CGF.SanOpts = OldSanOpts;
  770. }
  771. private:
  772. CodeGenFunction &CGF;
  773. SanitizerSet OldSanOpts;
  774. };
  775. } // end anonymous namespace
  776. namespace {
  777. class FieldMemcpyizer {
  778. public:
  779. FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
  780. const VarDecl *SrcRec)
  781. : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
  782. RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
  783. FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
  784. LastFieldOffset(0), LastAddedFieldIndex(0) {}
  785. bool isMemcpyableField(FieldDecl *F) const {
  786. // Never memcpy fields when we are adding poisoned paddings.
  787. if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
  788. return false;
  789. Qualifiers Qual = F->getType().getQualifiers();
  790. if (Qual.hasVolatile() || Qual.hasObjCLifetime())
  791. return false;
  792. return true;
  793. }
  794. void addMemcpyableField(FieldDecl *F) {
  795. if (F->isZeroSize(CGF.getContext()))
  796. return;
  797. if (!FirstField)
  798. addInitialField(F);
  799. else
  800. addNextField(F);
  801. }
  802. CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
  803. ASTContext &Ctx = CGF.getContext();
  804. unsigned LastFieldSize =
  805. LastField->isBitField()
  806. ? LastField->getBitWidthValue(Ctx)
  807. : Ctx.toBits(
  808. Ctx.getTypeInfoDataSizeInChars(LastField->getType()).Width);
  809. uint64_t MemcpySizeBits = LastFieldOffset + LastFieldSize -
  810. FirstByteOffset + Ctx.getCharWidth() - 1;
  811. CharUnits MemcpySize = Ctx.toCharUnitsFromBits(MemcpySizeBits);
  812. return MemcpySize;
  813. }
  814. void emitMemcpy() {
  815. // Give the subclass a chance to bail out if it feels the memcpy isn't
  816. // worth it (e.g. Hasn't aggregated enough data).
  817. if (!FirstField) {
  818. return;
  819. }
  820. uint64_t FirstByteOffset;
  821. if (FirstField->isBitField()) {
  822. const CGRecordLayout &RL =
  823. CGF.getTypes().getCGRecordLayout(FirstField->getParent());
  824. const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
  825. // FirstFieldOffset is not appropriate for bitfields,
  826. // we need to use the storage offset instead.
  827. FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
  828. } else {
  829. FirstByteOffset = FirstFieldOffset;
  830. }
  831. CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
  832. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  833. Address ThisPtr = CGF.LoadCXXThisAddress();
  834. LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy);
  835. LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
  836. llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
  837. LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
  838. LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
  839. emitMemcpyIR(
  840. Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(CGF),
  841. Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(CGF),
  842. MemcpySize);
  843. reset();
  844. }
  845. void reset() {
  846. FirstField = nullptr;
  847. }
  848. protected:
  849. CodeGenFunction &CGF;
  850. const CXXRecordDecl *ClassDecl;
  851. private:
  852. void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) {
  853. DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
  854. SrcPtr = CGF.Builder.CreateElementBitCast(SrcPtr, CGF.Int8Ty);
  855. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity());
  856. }
  857. void addInitialField(FieldDecl *F) {
  858. FirstField = F;
  859. LastField = F;
  860. FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  861. LastFieldOffset = FirstFieldOffset;
  862. LastAddedFieldIndex = F->getFieldIndex();
  863. }
  864. void addNextField(FieldDecl *F) {
  865. // For the most part, the following invariant will hold:
  866. // F->getFieldIndex() == LastAddedFieldIndex + 1
  867. // The one exception is that Sema won't add a copy-initializer for an
  868. // unnamed bitfield, which will show up here as a gap in the sequence.
  869. assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
  870. "Cannot aggregate fields out of order.");
  871. LastAddedFieldIndex = F->getFieldIndex();
  872. // The 'first' and 'last' fields are chosen by offset, rather than field
  873. // index. This allows the code to support bitfields, as well as regular
  874. // fields.
  875. uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
  876. if (FOffset < FirstFieldOffset) {
  877. FirstField = F;
  878. FirstFieldOffset = FOffset;
  879. } else if (FOffset >= LastFieldOffset) {
  880. LastField = F;
  881. LastFieldOffset = FOffset;
  882. }
  883. }
  884. const VarDecl *SrcRec;
  885. const ASTRecordLayout &RecLayout;
  886. FieldDecl *FirstField;
  887. FieldDecl *LastField;
  888. uint64_t FirstFieldOffset, LastFieldOffset;
  889. unsigned LastAddedFieldIndex;
  890. };
  891. class ConstructorMemcpyizer : public FieldMemcpyizer {
  892. private:
  893. /// Get source argument for copy constructor. Returns null if not a copy
  894. /// constructor.
  895. static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
  896. const CXXConstructorDecl *CD,
  897. FunctionArgList &Args) {
  898. if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
  899. return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
  900. return nullptr;
  901. }
  902. // Returns true if a CXXCtorInitializer represents a member initialization
  903. // that can be rolled into a memcpy.
  904. bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
  905. if (!MemcpyableCtor)
  906. return false;
  907. FieldDecl *Field = MemberInit->getMember();
  908. assert(Field && "No field for member init.");
  909. QualType FieldType = Field->getType();
  910. CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
  911. // Bail out on non-memcpyable, not-trivially-copyable members.
  912. if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
  913. !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
  914. FieldType->isReferenceType()))
  915. return false;
  916. // Bail out on volatile fields.
  917. if (!isMemcpyableField(Field))
  918. return false;
  919. // Otherwise we're good.
  920. return true;
  921. }
  922. public:
  923. ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
  924. FunctionArgList &Args)
  925. : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
  926. ConstructorDecl(CD),
  927. MemcpyableCtor(CD->isDefaulted() &&
  928. CD->isCopyOrMoveConstructor() &&
  929. CGF.getLangOpts().getGC() == LangOptions::NonGC),
  930. Args(Args) { }
  931. void addMemberInitializer(CXXCtorInitializer *MemberInit) {
  932. if (isMemberInitMemcpyable(MemberInit)) {
  933. AggregatedInits.push_back(MemberInit);
  934. addMemcpyableField(MemberInit->getMember());
  935. } else {
  936. emitAggregatedInits();
  937. EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
  938. ConstructorDecl, Args);
  939. }
  940. }
  941. void emitAggregatedInits() {
  942. if (AggregatedInits.size() <= 1) {
  943. // This memcpy is too small to be worthwhile. Fall back on default
  944. // codegen.
  945. if (!AggregatedInits.empty()) {
  946. CopyingValueRepresentation CVR(CGF);
  947. EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
  948. AggregatedInits[0], ConstructorDecl, Args);
  949. AggregatedInits.clear();
  950. }
  951. reset();
  952. return;
  953. }
  954. pushEHDestructors();
  955. emitMemcpy();
  956. AggregatedInits.clear();
  957. }
  958. void pushEHDestructors() {
  959. Address ThisPtr = CGF.LoadCXXThisAddress();
  960. QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
  961. LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy);
  962. for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
  963. CXXCtorInitializer *MemberInit = AggregatedInits[i];
  964. QualType FieldType = MemberInit->getAnyMember()->getType();
  965. QualType::DestructionKind dtorKind = FieldType.isDestructedType();
  966. if (!CGF.needsEHCleanup(dtorKind))
  967. continue;
  968. LValue FieldLHS = LHS;
  969. EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
  970. CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(CGF), FieldType);
  971. }
  972. }
  973. void finish() {
  974. emitAggregatedInits();
  975. }
  976. private:
  977. const CXXConstructorDecl *ConstructorDecl;
  978. bool MemcpyableCtor;
  979. FunctionArgList &Args;
  980. SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
  981. };
  982. class AssignmentMemcpyizer : public FieldMemcpyizer {
  983. private:
  984. // Returns the memcpyable field copied by the given statement, if one
  985. // exists. Otherwise returns null.
  986. FieldDecl *getMemcpyableField(Stmt *S) {
  987. if (!AssignmentsMemcpyable)
  988. return nullptr;
  989. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
  990. // Recognise trivial assignments.
  991. if (BO->getOpcode() != BO_Assign)
  992. return nullptr;
  993. MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
  994. if (!ME)
  995. return nullptr;
  996. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  997. if (!Field || !isMemcpyableField(Field))
  998. return nullptr;
  999. Stmt *RHS = BO->getRHS();
  1000. if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
  1001. RHS = EC->getSubExpr();
  1002. if (!RHS)
  1003. return nullptr;
  1004. if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) {
  1005. if (ME2->getMemberDecl() == Field)
  1006. return Field;
  1007. }
  1008. return nullptr;
  1009. } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
  1010. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
  1011. if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
  1012. return nullptr;
  1013. MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
  1014. if (!IOA)
  1015. return nullptr;
  1016. FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
  1017. if (!Field || !isMemcpyableField(Field))
  1018. return nullptr;
  1019. MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
  1020. if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
  1021. return nullptr;
  1022. return Field;
  1023. } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
  1024. FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  1025. if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
  1026. return nullptr;
  1027. Expr *DstPtr = CE->getArg(0);
  1028. if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
  1029. DstPtr = DC->getSubExpr();
  1030. UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
  1031. if (!DUO || DUO->getOpcode() != UO_AddrOf)
  1032. return nullptr;
  1033. MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
  1034. if (!ME)
  1035. return nullptr;
  1036. FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
  1037. if (!Field || !isMemcpyableField(Field))
  1038. return nullptr;
  1039. Expr *SrcPtr = CE->getArg(1);
  1040. if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
  1041. SrcPtr = SC->getSubExpr();
  1042. UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
  1043. if (!SUO || SUO->getOpcode() != UO_AddrOf)
  1044. return nullptr;
  1045. MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
  1046. if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
  1047. return nullptr;
  1048. return Field;
  1049. }
  1050. return nullptr;
  1051. }
  1052. bool AssignmentsMemcpyable;
  1053. SmallVector<Stmt*, 16> AggregatedStmts;
  1054. public:
  1055. AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
  1056. FunctionArgList &Args)
  1057. : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
  1058. AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
  1059. assert(Args.size() == 2);
  1060. }
  1061. void emitAssignment(Stmt *S) {
  1062. FieldDecl *F = getMemcpyableField(S);
  1063. if (F) {
  1064. addMemcpyableField(F);
  1065. AggregatedStmts.push_back(S);
  1066. } else {
  1067. emitAggregatedStmts();
  1068. CGF.EmitStmt(S);
  1069. }
  1070. }
  1071. void emitAggregatedStmts() {
  1072. if (AggregatedStmts.size() <= 1) {
  1073. if (!AggregatedStmts.empty()) {
  1074. CopyingValueRepresentation CVR(CGF);
  1075. CGF.EmitStmt(AggregatedStmts[0]);
  1076. }
  1077. reset();
  1078. }
  1079. emitMemcpy();
  1080. AggregatedStmts.clear();
  1081. }
  1082. void finish() {
  1083. emitAggregatedStmts();
  1084. }
  1085. };
  1086. } // end anonymous namespace
  1087. static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) {
  1088. const Type *BaseType = BaseInit->getBaseClass();
  1089. const auto *BaseClassDecl =
  1090. cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
  1091. return BaseClassDecl->isDynamicClass();
  1092. }
  1093. /// EmitCtorPrologue - This routine generates necessary code to initialize
  1094. /// base classes and non-static data members belonging to this constructor.
  1095. void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
  1096. CXXCtorType CtorType,
  1097. FunctionArgList &Args) {
  1098. if (CD->isDelegatingConstructor())
  1099. return EmitDelegatingCXXConstructorCall(CD, Args);
  1100. const CXXRecordDecl *ClassDecl = CD->getParent();
  1101. CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
  1102. E = CD->init_end();
  1103. // Virtual base initializers first, if any. They aren't needed if:
  1104. // - This is a base ctor variant
  1105. // - There are no vbases
  1106. // - The class is abstract, so a complete object of it cannot be constructed
  1107. //
  1108. // The check for an abstract class is necessary because sema may not have
  1109. // marked virtual base destructors referenced.
  1110. bool ConstructVBases = CtorType != Ctor_Base &&
  1111. ClassDecl->getNumVBases() != 0 &&
  1112. !ClassDecl->isAbstract();
  1113. // In the Microsoft C++ ABI, there are no constructor variants. Instead, the
  1114. // constructor of a class with virtual bases takes an additional parameter to
  1115. // conditionally construct the virtual bases. Emit that check here.
  1116. llvm::BasicBlock *BaseCtorContinueBB = nullptr;
  1117. if (ConstructVBases &&
  1118. !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1119. BaseCtorContinueBB =
  1120. CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
  1121. assert(BaseCtorContinueBB);
  1122. }
  1123. llvm::Value *const OldThis = CXXThisValue;
  1124. for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
  1125. if (!ConstructVBases)
  1126. continue;
  1127. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1128. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1129. isInitializerOfDynamicClass(*B))
  1130. CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
  1131. EmitBaseInitializer(*this, ClassDecl, *B);
  1132. }
  1133. if (BaseCtorContinueBB) {
  1134. // Complete object handler should continue to the remaining initializers.
  1135. Builder.CreateBr(BaseCtorContinueBB);
  1136. EmitBlock(BaseCtorContinueBB);
  1137. }
  1138. // Then, non-virtual base initializers.
  1139. for (; B != E && (*B)->isBaseInitializer(); B++) {
  1140. assert(!(*B)->isBaseVirtual());
  1141. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1142. CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1143. isInitializerOfDynamicClass(*B))
  1144. CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
  1145. EmitBaseInitializer(*this, ClassDecl, *B);
  1146. }
  1147. CXXThisValue = OldThis;
  1148. InitializeVTablePointers(ClassDecl);
  1149. // And finally, initialize class members.
  1150. FieldConstructionScope FCS(*this, LoadCXXThisAddress());
  1151. ConstructorMemcpyizer CM(*this, CD, Args);
  1152. for (; B != E; B++) {
  1153. CXXCtorInitializer *Member = (*B);
  1154. assert(!Member->isBaseInitializer());
  1155. assert(Member->isAnyMemberInitializer() &&
  1156. "Delegating initializer on non-delegating constructor");
  1157. CM.addMemberInitializer(Member);
  1158. }
  1159. CM.finish();
  1160. }
  1161. static bool
  1162. FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
  1163. static bool
  1164. HasTrivialDestructorBody(ASTContext &Context,
  1165. const CXXRecordDecl *BaseClassDecl,
  1166. const CXXRecordDecl *MostDerivedClassDecl)
  1167. {
  1168. // If the destructor is trivial we don't have to check anything else.
  1169. if (BaseClassDecl->hasTrivialDestructor())
  1170. return true;
  1171. if (!BaseClassDecl->getDestructor()->hasTrivialBody())
  1172. return false;
  1173. // Check fields.
  1174. for (const auto *Field : BaseClassDecl->fields())
  1175. if (!FieldHasTrivialDestructorBody(Context, Field))
  1176. return false;
  1177. // Check non-virtual bases.
  1178. for (const auto &I : BaseClassDecl->bases()) {
  1179. if (I.isVirtual())
  1180. continue;
  1181. const CXXRecordDecl *NonVirtualBase =
  1182. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1183. if (!HasTrivialDestructorBody(Context, NonVirtualBase,
  1184. MostDerivedClassDecl))
  1185. return false;
  1186. }
  1187. if (BaseClassDecl == MostDerivedClassDecl) {
  1188. // Check virtual bases.
  1189. for (const auto &I : BaseClassDecl->vbases()) {
  1190. const CXXRecordDecl *VirtualBase =
  1191. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1192. if (!HasTrivialDestructorBody(Context, VirtualBase,
  1193. MostDerivedClassDecl))
  1194. return false;
  1195. }
  1196. }
  1197. return true;
  1198. }
  1199. static bool
  1200. FieldHasTrivialDestructorBody(ASTContext &Context,
  1201. const FieldDecl *Field)
  1202. {
  1203. QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
  1204. const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
  1205. if (!RT)
  1206. return true;
  1207. CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  1208. // The destructor for an implicit anonymous union member is never invoked.
  1209. if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
  1210. return false;
  1211. return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
  1212. }
  1213. /// CanSkipVTablePointerInitialization - Check whether we need to initialize
  1214. /// any vtable pointers before calling this destructor.
  1215. static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
  1216. const CXXDestructorDecl *Dtor) {
  1217. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1218. if (!ClassDecl->isDynamicClass())
  1219. return true;
  1220. // For a final class, the vtable pointer is known to already point to the
  1221. // class's vtable.
  1222. if (ClassDecl->isEffectivelyFinal())
  1223. return true;
  1224. if (!Dtor->hasTrivialBody())
  1225. return false;
  1226. // Check the fields.
  1227. for (const auto *Field : ClassDecl->fields())
  1228. if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
  1229. return false;
  1230. return true;
  1231. }
  1232. /// EmitDestructorBody - Emits the body of the current destructor.
  1233. void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
  1234. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
  1235. CXXDtorType DtorType = CurGD.getDtorType();
  1236. // For an abstract class, non-base destructors are never used (and can't
  1237. // be emitted in general, because vbase dtors may not have been validated
  1238. // by Sema), but the Itanium ABI doesn't make them optional and Clang may
  1239. // in fact emit references to them from other compilations, so emit them
  1240. // as functions containing a trap instruction.
  1241. if (DtorType != Dtor_Base && Dtor->getParent()->isAbstract()) {
  1242. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  1243. TrapCall->setDoesNotReturn();
  1244. TrapCall->setDoesNotThrow();
  1245. Builder.CreateUnreachable();
  1246. Builder.ClearInsertionPoint();
  1247. return;
  1248. }
  1249. Stmt *Body = Dtor->getBody();
  1250. if (Body)
  1251. incrementProfileCounter(Body);
  1252. // The call to operator delete in a deleting destructor happens
  1253. // outside of the function-try-block, which means it's always
  1254. // possible to delegate the destructor body to the complete
  1255. // destructor. Do so.
  1256. if (DtorType == Dtor_Deleting) {
  1257. RunCleanupsScope DtorEpilogue(*this);
  1258. EnterDtorCleanups(Dtor, Dtor_Deleting);
  1259. if (HaveInsertPoint()) {
  1260. QualType ThisTy = Dtor->getThisObjectType();
  1261. EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
  1262. /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
  1263. }
  1264. return;
  1265. }
  1266. // If the body is a function-try-block, enter the try before
  1267. // anything else.
  1268. bool isTryBody = (Body && isa<CXXTryStmt>(Body));
  1269. if (isTryBody)
  1270. EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1271. EmitAsanPrologueOrEpilogue(false);
  1272. // Enter the epilogue cleanups.
  1273. RunCleanupsScope DtorEpilogue(*this);
  1274. // If this is the complete variant, just invoke the base variant;
  1275. // the epilogue will destruct the virtual bases. But we can't do
  1276. // this optimization if the body is a function-try-block, because
  1277. // we'd introduce *two* handler blocks. In the Microsoft ABI, we
  1278. // always delegate because we might not have a definition in this TU.
  1279. switch (DtorType) {
  1280. case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT");
  1281. case Dtor_Deleting: llvm_unreachable("already handled deleting case");
  1282. case Dtor_Complete:
  1283. assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
  1284. "can't emit a dtor without a body for non-Microsoft ABIs");
  1285. // Enter the cleanup scopes for virtual bases.
  1286. EnterDtorCleanups(Dtor, Dtor_Complete);
  1287. if (!isTryBody) {
  1288. QualType ThisTy = Dtor->getThisObjectType();
  1289. EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
  1290. /*Delegating=*/false, LoadCXXThisAddress(), ThisTy);
  1291. break;
  1292. }
  1293. // Fallthrough: act like we're in the base variant.
  1294. [[fallthrough]];
  1295. case Dtor_Base:
  1296. assert(Body);
  1297. // Enter the cleanup scopes for fields and non-virtual bases.
  1298. EnterDtorCleanups(Dtor, Dtor_Base);
  1299. // Initialize the vtable pointers before entering the body.
  1300. if (!CanSkipVTablePointerInitialization(*this, Dtor)) {
  1301. // Insert the llvm.launder.invariant.group intrinsic before initializing
  1302. // the vptrs to cancel any previous assumptions we might have made.
  1303. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  1304. CGM.getCodeGenOpts().OptimizationLevel > 0)
  1305. CXXThisValue = Builder.CreateLaunderInvariantGroup(LoadCXXThis());
  1306. InitializeVTablePointers(Dtor->getParent());
  1307. }
  1308. if (isTryBody)
  1309. EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
  1310. else if (Body)
  1311. EmitStmt(Body);
  1312. else {
  1313. assert(Dtor->isImplicit() && "bodyless dtor not implicit");
  1314. // nothing to do besides what's in the epilogue
  1315. }
  1316. // -fapple-kext must inline any call to this dtor into
  1317. // the caller's body.
  1318. if (getLangOpts().AppleKext)
  1319. CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
  1320. break;
  1321. }
  1322. // Jump out through the epilogue cleanups.
  1323. DtorEpilogue.ForceCleanup();
  1324. // Exit the try if applicable.
  1325. if (isTryBody)
  1326. ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
  1327. }
  1328. void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
  1329. const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
  1330. const Stmt *RootS = AssignOp->getBody();
  1331. assert(isa<CompoundStmt>(RootS) &&
  1332. "Body of an implicit assignment operator should be compound stmt.");
  1333. const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
  1334. LexicalScope Scope(*this, RootCS->getSourceRange());
  1335. incrementProfileCounter(RootCS);
  1336. AssignmentMemcpyizer AM(*this, AssignOp, Args);
  1337. for (auto *I : RootCS->body())
  1338. AM.emitAssignment(I);
  1339. AM.finish();
  1340. }
  1341. namespace {
  1342. llvm::Value *LoadThisForDtorDelete(CodeGenFunction &CGF,
  1343. const CXXDestructorDecl *DD) {
  1344. if (Expr *ThisArg = DD->getOperatorDeleteThisArg())
  1345. return CGF.EmitScalarExpr(ThisArg);
  1346. return CGF.LoadCXXThis();
  1347. }
  1348. /// Call the operator delete associated with the current destructor.
  1349. struct CallDtorDelete final : EHScopeStack::Cleanup {
  1350. CallDtorDelete() {}
  1351. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1352. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1353. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1354. CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
  1355. LoadThisForDtorDelete(CGF, Dtor),
  1356. CGF.getContext().getTagDeclType(ClassDecl));
  1357. }
  1358. };
  1359. void EmitConditionalDtorDeleteCall(CodeGenFunction &CGF,
  1360. llvm::Value *ShouldDeleteCondition,
  1361. bool ReturnAfterDelete) {
  1362. llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
  1363. llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
  1364. llvm::Value *ShouldCallDelete
  1365. = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
  1366. CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
  1367. CGF.EmitBlock(callDeleteBB);
  1368. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
  1369. const CXXRecordDecl *ClassDecl = Dtor->getParent();
  1370. CGF.EmitDeleteCall(Dtor->getOperatorDelete(),
  1371. LoadThisForDtorDelete(CGF, Dtor),
  1372. CGF.getContext().getTagDeclType(ClassDecl));
  1373. assert(Dtor->getOperatorDelete()->isDestroyingOperatorDelete() ==
  1374. ReturnAfterDelete &&
  1375. "unexpected value for ReturnAfterDelete");
  1376. if (ReturnAfterDelete)
  1377. CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
  1378. else
  1379. CGF.Builder.CreateBr(continueBB);
  1380. CGF.EmitBlock(continueBB);
  1381. }
  1382. struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
  1383. llvm::Value *ShouldDeleteCondition;
  1384. public:
  1385. CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
  1386. : ShouldDeleteCondition(ShouldDeleteCondition) {
  1387. assert(ShouldDeleteCondition != nullptr);
  1388. }
  1389. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1390. EmitConditionalDtorDeleteCall(CGF, ShouldDeleteCondition,
  1391. /*ReturnAfterDelete*/false);
  1392. }
  1393. };
  1394. class DestroyField final : public EHScopeStack::Cleanup {
  1395. const FieldDecl *field;
  1396. CodeGenFunction::Destroyer *destroyer;
  1397. bool useEHCleanupForArray;
  1398. public:
  1399. DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
  1400. bool useEHCleanupForArray)
  1401. : field(field), destroyer(destroyer),
  1402. useEHCleanupForArray(useEHCleanupForArray) {}
  1403. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1404. // Find the address of the field.
  1405. Address thisValue = CGF.LoadCXXThisAddress();
  1406. QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
  1407. LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
  1408. LValue LV = CGF.EmitLValueForField(ThisLV, field);
  1409. assert(LV.isSimple());
  1410. CGF.emitDestroy(LV.getAddress(CGF), field->getType(), destroyer,
  1411. flags.isForNormalCleanup() && useEHCleanupForArray);
  1412. }
  1413. };
  1414. class DeclAsInlineDebugLocation {
  1415. CGDebugInfo *DI;
  1416. llvm::MDNode *InlinedAt;
  1417. std::optional<ApplyDebugLocation> Location;
  1418. public:
  1419. DeclAsInlineDebugLocation(CodeGenFunction &CGF, const NamedDecl &Decl)
  1420. : DI(CGF.getDebugInfo()) {
  1421. if (!DI)
  1422. return;
  1423. InlinedAt = DI->getInlinedAt();
  1424. DI->setInlinedAt(CGF.Builder.getCurrentDebugLocation());
  1425. Location.emplace(CGF, Decl.getLocation());
  1426. }
  1427. ~DeclAsInlineDebugLocation() {
  1428. if (!DI)
  1429. return;
  1430. Location.reset();
  1431. DI->setInlinedAt(InlinedAt);
  1432. }
  1433. };
  1434. static void EmitSanitizerDtorCallback(
  1435. CodeGenFunction &CGF, StringRef Name, llvm::Value *Ptr,
  1436. std::optional<CharUnits::QuantityType> PoisonSize = {}) {
  1437. CodeGenFunction::SanitizerScope SanScope(&CGF);
  1438. // Pass in void pointer and size of region as arguments to runtime
  1439. // function
  1440. SmallVector<llvm::Value *, 2> Args = {
  1441. CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy)};
  1442. SmallVector<llvm::Type *, 2> ArgTypes = {CGF.VoidPtrTy};
  1443. if (PoisonSize.has_value()) {
  1444. Args.emplace_back(llvm::ConstantInt::get(CGF.SizeTy, *PoisonSize));
  1445. ArgTypes.emplace_back(CGF.SizeTy);
  1446. }
  1447. llvm::FunctionType *FnType =
  1448. llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
  1449. llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FnType, Name);
  1450. CGF.EmitNounwindRuntimeCall(Fn, Args);
  1451. }
  1452. static void
  1453. EmitSanitizerDtorFieldsCallback(CodeGenFunction &CGF, llvm::Value *Ptr,
  1454. CharUnits::QuantityType PoisonSize) {
  1455. EmitSanitizerDtorCallback(CGF, "__sanitizer_dtor_callback_fields", Ptr,
  1456. PoisonSize);
  1457. }
  1458. /// Poison base class with a trivial destructor.
  1459. struct SanitizeDtorTrivialBase final : EHScopeStack::Cleanup {
  1460. const CXXRecordDecl *BaseClass;
  1461. bool BaseIsVirtual;
  1462. SanitizeDtorTrivialBase(const CXXRecordDecl *Base, bool BaseIsVirtual)
  1463. : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
  1464. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1465. const CXXRecordDecl *DerivedClass =
  1466. cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
  1467. Address Addr = CGF.GetAddressOfDirectBaseInCompleteClass(
  1468. CGF.LoadCXXThisAddress(), DerivedClass, BaseClass, BaseIsVirtual);
  1469. const ASTRecordLayout &BaseLayout =
  1470. CGF.getContext().getASTRecordLayout(BaseClass);
  1471. CharUnits BaseSize = BaseLayout.getSize();
  1472. if (!BaseSize.isPositive())
  1473. return;
  1474. // Use the base class declaration location as inline DebugLocation. All
  1475. // fields of the class are destroyed.
  1476. DeclAsInlineDebugLocation InlineHere(CGF, *BaseClass);
  1477. EmitSanitizerDtorFieldsCallback(CGF, Addr.getPointer(),
  1478. BaseSize.getQuantity());
  1479. // Prevent the current stack frame from disappearing from the stack trace.
  1480. CGF.CurFn->addFnAttr("disable-tail-calls", "true");
  1481. }
  1482. };
  1483. class SanitizeDtorFieldRange final : public EHScopeStack::Cleanup {
  1484. const CXXDestructorDecl *Dtor;
  1485. unsigned StartIndex;
  1486. unsigned EndIndex;
  1487. public:
  1488. SanitizeDtorFieldRange(const CXXDestructorDecl *Dtor, unsigned StartIndex,
  1489. unsigned EndIndex)
  1490. : Dtor(Dtor), StartIndex(StartIndex), EndIndex(EndIndex) {}
  1491. // Generate function call for handling object poisoning.
  1492. // Disables tail call elimination, to prevent the current stack frame
  1493. // from disappearing from the stack trace.
  1494. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1495. const ASTContext &Context = CGF.getContext();
  1496. const ASTRecordLayout &Layout =
  1497. Context.getASTRecordLayout(Dtor->getParent());
  1498. // It's a first trivial field so it should be at the begining of a char,
  1499. // still round up start offset just in case.
  1500. CharUnits PoisonStart = Context.toCharUnitsFromBits(
  1501. Layout.getFieldOffset(StartIndex) + Context.getCharWidth() - 1);
  1502. llvm::ConstantInt *OffsetSizePtr =
  1503. llvm::ConstantInt::get(CGF.SizeTy, PoisonStart.getQuantity());
  1504. llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
  1505. CGF.Int8Ty,
  1506. CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
  1507. OffsetSizePtr);
  1508. CharUnits PoisonEnd;
  1509. if (EndIndex >= Layout.getFieldCount()) {
  1510. PoisonEnd = Layout.getNonVirtualSize();
  1511. } else {
  1512. PoisonEnd =
  1513. Context.toCharUnitsFromBits(Layout.getFieldOffset(EndIndex));
  1514. }
  1515. CharUnits PoisonSize = PoisonEnd - PoisonStart;
  1516. if (!PoisonSize.isPositive())
  1517. return;
  1518. // Use the top field declaration location as inline DebugLocation.
  1519. DeclAsInlineDebugLocation InlineHere(
  1520. CGF, **std::next(Dtor->getParent()->field_begin(), StartIndex));
  1521. EmitSanitizerDtorFieldsCallback(CGF, OffsetPtr, PoisonSize.getQuantity());
  1522. // Prevent the current stack frame from disappearing from the stack trace.
  1523. CGF.CurFn->addFnAttr("disable-tail-calls", "true");
  1524. }
  1525. };
  1526. class SanitizeDtorVTable final : public EHScopeStack::Cleanup {
  1527. const CXXDestructorDecl *Dtor;
  1528. public:
  1529. SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
  1530. // Generate function call for handling vtable pointer poisoning.
  1531. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1532. assert(Dtor->getParent()->isDynamicClass());
  1533. (void)Dtor;
  1534. // Poison vtable and vtable ptr if they exist for this class.
  1535. llvm::Value *VTablePtr = CGF.LoadCXXThis();
  1536. // Pass in void pointer and size of region as arguments to runtime
  1537. // function
  1538. EmitSanitizerDtorCallback(CGF, "__sanitizer_dtor_callback_vptr",
  1539. VTablePtr);
  1540. }
  1541. };
  1542. class SanitizeDtorCleanupBuilder {
  1543. ASTContext &Context;
  1544. EHScopeStack &EHStack;
  1545. const CXXDestructorDecl *DD;
  1546. std::optional<unsigned> StartIndex;
  1547. public:
  1548. SanitizeDtorCleanupBuilder(ASTContext &Context, EHScopeStack &EHStack,
  1549. const CXXDestructorDecl *DD)
  1550. : Context(Context), EHStack(EHStack), DD(DD), StartIndex(std::nullopt) {}
  1551. void PushCleanupForField(const FieldDecl *Field) {
  1552. if (Field->isZeroSize(Context))
  1553. return;
  1554. unsigned FieldIndex = Field->getFieldIndex();
  1555. if (FieldHasTrivialDestructorBody(Context, Field)) {
  1556. if (!StartIndex)
  1557. StartIndex = FieldIndex;
  1558. } else if (StartIndex) {
  1559. EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
  1560. *StartIndex, FieldIndex);
  1561. StartIndex = std::nullopt;
  1562. }
  1563. }
  1564. void End() {
  1565. if (StartIndex)
  1566. EHStack.pushCleanup<SanitizeDtorFieldRange>(NormalAndEHCleanup, DD,
  1567. *StartIndex, -1);
  1568. }
  1569. };
  1570. } // end anonymous namespace
  1571. /// Emit all code that comes at the end of class's
  1572. /// destructor. This is to call destructors on members and base classes
  1573. /// in reverse order of their construction.
  1574. ///
  1575. /// For a deleting destructor, this also handles the case where a destroying
  1576. /// operator delete completely overrides the definition.
  1577. void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
  1578. CXXDtorType DtorType) {
  1579. assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
  1580. "Should not emit dtor epilogue for non-exported trivial dtor!");
  1581. // The deleting-destructor phase just needs to call the appropriate
  1582. // operator delete that Sema picked up.
  1583. if (DtorType == Dtor_Deleting) {
  1584. assert(DD->getOperatorDelete() &&
  1585. "operator delete missing - EnterDtorCleanups");
  1586. if (CXXStructorImplicitParamValue) {
  1587. // If there is an implicit param to the deleting dtor, it's a boolean
  1588. // telling whether this is a deleting destructor.
  1589. if (DD->getOperatorDelete()->isDestroyingOperatorDelete())
  1590. EmitConditionalDtorDeleteCall(*this, CXXStructorImplicitParamValue,
  1591. /*ReturnAfterDelete*/true);
  1592. else
  1593. EHStack.pushCleanup<CallDtorDeleteConditional>(
  1594. NormalAndEHCleanup, CXXStructorImplicitParamValue);
  1595. } else {
  1596. if (DD->getOperatorDelete()->isDestroyingOperatorDelete()) {
  1597. const CXXRecordDecl *ClassDecl = DD->getParent();
  1598. EmitDeleteCall(DD->getOperatorDelete(),
  1599. LoadThisForDtorDelete(*this, DD),
  1600. getContext().getTagDeclType(ClassDecl));
  1601. EmitBranchThroughCleanup(ReturnBlock);
  1602. } else {
  1603. EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
  1604. }
  1605. }
  1606. return;
  1607. }
  1608. const CXXRecordDecl *ClassDecl = DD->getParent();
  1609. // Unions have no bases and do not call field destructors.
  1610. if (ClassDecl->isUnion())
  1611. return;
  1612. // The complete-destructor phase just destructs all the virtual bases.
  1613. if (DtorType == Dtor_Complete) {
  1614. // Poison the vtable pointer such that access after the base
  1615. // and member destructors are invoked is invalid.
  1616. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1617. SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() &&
  1618. ClassDecl->isPolymorphic())
  1619. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1620. // We push them in the forward order so that they'll be popped in
  1621. // the reverse order.
  1622. for (const auto &Base : ClassDecl->vbases()) {
  1623. auto *BaseClassDecl =
  1624. cast<CXXRecordDecl>(Base.getType()->castAs<RecordType>()->getDecl());
  1625. if (BaseClassDecl->hasTrivialDestructor()) {
  1626. // Under SanitizeMemoryUseAfterDtor, poison the trivial base class
  1627. // memory. For non-trival base classes the same is done in the class
  1628. // destructor.
  1629. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1630. SanOpts.has(SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
  1631. EHStack.pushCleanup<SanitizeDtorTrivialBase>(NormalAndEHCleanup,
  1632. BaseClassDecl,
  1633. /*BaseIsVirtual*/ true);
  1634. } else {
  1635. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, BaseClassDecl,
  1636. /*BaseIsVirtual*/ true);
  1637. }
  1638. }
  1639. return;
  1640. }
  1641. assert(DtorType == Dtor_Base);
  1642. // Poison the vtable pointer if it has no virtual bases, but inherits
  1643. // virtual functions.
  1644. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1645. SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() &&
  1646. ClassDecl->isPolymorphic())
  1647. EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD);
  1648. // Destroy non-virtual bases.
  1649. for (const auto &Base : ClassDecl->bases()) {
  1650. // Ignore virtual bases.
  1651. if (Base.isVirtual())
  1652. continue;
  1653. CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
  1654. if (BaseClassDecl->hasTrivialDestructor()) {
  1655. if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1656. SanOpts.has(SanitizerKind::Memory) && !BaseClassDecl->isEmpty())
  1657. EHStack.pushCleanup<SanitizeDtorTrivialBase>(NormalAndEHCleanup,
  1658. BaseClassDecl,
  1659. /*BaseIsVirtual*/ false);
  1660. } else {
  1661. EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, BaseClassDecl,
  1662. /*BaseIsVirtual*/ false);
  1663. }
  1664. }
  1665. // Poison fields such that access after their destructors are
  1666. // invoked, and before the base class destructor runs, is invalid.
  1667. bool SanitizeFields = CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
  1668. SanOpts.has(SanitizerKind::Memory);
  1669. SanitizeDtorCleanupBuilder SanitizeBuilder(getContext(), EHStack, DD);
  1670. // Destroy direct fields.
  1671. for (const auto *Field : ClassDecl->fields()) {
  1672. if (SanitizeFields)
  1673. SanitizeBuilder.PushCleanupForField(Field);
  1674. QualType type = Field->getType();
  1675. QualType::DestructionKind dtorKind = type.isDestructedType();
  1676. if (!dtorKind)
  1677. continue;
  1678. // Anonymous union members do not have their destructors called.
  1679. const RecordType *RT = type->getAsUnionType();
  1680. if (RT && RT->getDecl()->isAnonymousStructOrUnion())
  1681. continue;
  1682. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1683. EHStack.pushCleanup<DestroyField>(
  1684. cleanupKind, Field, getDestroyer(dtorKind), cleanupKind & EHCleanup);
  1685. }
  1686. if (SanitizeFields)
  1687. SanitizeBuilder.End();
  1688. }
  1689. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1690. /// constructor for each of several members of an array.
  1691. ///
  1692. /// \param ctor the constructor to call for each element
  1693. /// \param arrayType the type of the array to initialize
  1694. /// \param arrayBegin an arrayType*
  1695. /// \param zeroInitialize true if each element should be
  1696. /// zero-initialized before it is constructed
  1697. void CodeGenFunction::EmitCXXAggrConstructorCall(
  1698. const CXXConstructorDecl *ctor, const ArrayType *arrayType,
  1699. Address arrayBegin, const CXXConstructExpr *E, bool NewPointerIsChecked,
  1700. bool zeroInitialize) {
  1701. QualType elementType;
  1702. llvm::Value *numElements =
  1703. emitArrayLength(arrayType, elementType, arrayBegin);
  1704. EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E,
  1705. NewPointerIsChecked, zeroInitialize);
  1706. }
  1707. /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
  1708. /// constructor for each of several members of an array.
  1709. ///
  1710. /// \param ctor the constructor to call for each element
  1711. /// \param numElements the number of elements in the array;
  1712. /// may be zero
  1713. /// \param arrayBase a T*, where T is the type constructed by ctor
  1714. /// \param zeroInitialize true if each element should be
  1715. /// zero-initialized before it is constructed
  1716. void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
  1717. llvm::Value *numElements,
  1718. Address arrayBase,
  1719. const CXXConstructExpr *E,
  1720. bool NewPointerIsChecked,
  1721. bool zeroInitialize) {
  1722. // It's legal for numElements to be zero. This can happen both
  1723. // dynamically, because x can be zero in 'new A[x]', and statically,
  1724. // because of GCC extensions that permit zero-length arrays. There
  1725. // are probably legitimate places where we could assume that this
  1726. // doesn't happen, but it's not clear that it's worth it.
  1727. llvm::BranchInst *zeroCheckBranch = nullptr;
  1728. // Optimize for a constant count.
  1729. llvm::ConstantInt *constantCount
  1730. = dyn_cast<llvm::ConstantInt>(numElements);
  1731. if (constantCount) {
  1732. // Just skip out if the constant count is zero.
  1733. if (constantCount->isZero()) return;
  1734. // Otherwise, emit the check.
  1735. } else {
  1736. llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
  1737. llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
  1738. zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
  1739. EmitBlock(loopBB);
  1740. }
  1741. // Find the end of the array.
  1742. llvm::Type *elementType = arrayBase.getElementType();
  1743. llvm::Value *arrayBegin = arrayBase.getPointer();
  1744. llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(
  1745. elementType, arrayBegin, numElements, "arrayctor.end");
  1746. // Enter the loop, setting up a phi for the current location to initialize.
  1747. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1748. llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
  1749. EmitBlock(loopBB);
  1750. llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
  1751. "arrayctor.cur");
  1752. cur->addIncoming(arrayBegin, entryBB);
  1753. // Inside the loop body, emit the constructor call on the array element.
  1754. // The alignment of the base, adjusted by the size of a single element,
  1755. // provides a conservative estimate of the alignment of every element.
  1756. // (This assumes we never start tracking offsetted alignments.)
  1757. //
  1758. // Note that these are complete objects and so we don't need to
  1759. // use the non-virtual size or alignment.
  1760. QualType type = getContext().getTypeDeclType(ctor->getParent());
  1761. CharUnits eltAlignment =
  1762. arrayBase.getAlignment()
  1763. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1764. Address curAddr = Address(cur, elementType, eltAlignment);
  1765. // Zero initialize the storage, if requested.
  1766. if (zeroInitialize)
  1767. EmitNullInitialization(curAddr, type);
  1768. // C++ [class.temporary]p4:
  1769. // There are two contexts in which temporaries are destroyed at a different
  1770. // point than the end of the full-expression. The first context is when a
  1771. // default constructor is called to initialize an element of an array.
  1772. // If the constructor has one or more default arguments, the destruction of
  1773. // every temporary created in a default argument expression is sequenced
  1774. // before the construction of the next array element, if any.
  1775. {
  1776. RunCleanupsScope Scope(*this);
  1777. // Evaluate the constructor and its arguments in a regular
  1778. // partial-destroy cleanup.
  1779. if (getLangOpts().Exceptions &&
  1780. !ctor->getParent()->hasTrivialDestructor()) {
  1781. Destroyer *destroyer = destroyCXXObject;
  1782. pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment,
  1783. *destroyer);
  1784. }
  1785. auto currAVS = AggValueSlot::forAddr(
  1786. curAddr, type.getQualifiers(), AggValueSlot::IsDestructed,
  1787. AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased,
  1788. AggValueSlot::DoesNotOverlap, AggValueSlot::IsNotZeroed,
  1789. NewPointerIsChecked ? AggValueSlot::IsSanitizerChecked
  1790. : AggValueSlot::IsNotSanitizerChecked);
  1791. EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
  1792. /*Delegating=*/false, currAVS, E);
  1793. }
  1794. // Go to the next element.
  1795. llvm::Value *next = Builder.CreateInBoundsGEP(
  1796. elementType, cur, llvm::ConstantInt::get(SizeTy, 1), "arrayctor.next");
  1797. cur->addIncoming(next, Builder.GetInsertBlock());
  1798. // Check whether that's the end of the loop.
  1799. llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
  1800. llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
  1801. Builder.CreateCondBr(done, contBB, loopBB);
  1802. // Patch the earlier check to skip over the loop.
  1803. if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
  1804. EmitBlock(contBB);
  1805. }
  1806. void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
  1807. Address addr,
  1808. QualType type) {
  1809. const RecordType *rtype = type->castAs<RecordType>();
  1810. const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
  1811. const CXXDestructorDecl *dtor = record->getDestructor();
  1812. assert(!dtor->isTrivial());
  1813. CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
  1814. /*Delegating=*/false, addr, type);
  1815. }
  1816. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1817. CXXCtorType Type,
  1818. bool ForVirtualBase,
  1819. bool Delegating,
  1820. AggValueSlot ThisAVS,
  1821. const CXXConstructExpr *E) {
  1822. CallArgList Args;
  1823. Address This = ThisAVS.getAddress();
  1824. LangAS SlotAS = ThisAVS.getQualifiers().getAddressSpace();
  1825. QualType ThisType = D->getThisType();
  1826. LangAS ThisAS = ThisType.getTypePtr()->getPointeeType().getAddressSpace();
  1827. llvm::Value *ThisPtr = This.getPointer();
  1828. if (SlotAS != ThisAS) {
  1829. unsigned TargetThisAS = getContext().getTargetAddressSpace(ThisAS);
  1830. llvm::Type *NewType = llvm::PointerType::getWithSamePointeeType(
  1831. This.getType(), TargetThisAS);
  1832. ThisPtr = getTargetHooks().performAddrSpaceCast(*this, This.getPointer(),
  1833. ThisAS, SlotAS, NewType);
  1834. }
  1835. // Push the this ptr.
  1836. Args.add(RValue::get(ThisPtr), D->getThisType());
  1837. // If this is a trivial constructor, emit a memcpy now before we lose
  1838. // the alignment information on the argument.
  1839. // FIXME: It would be better to preserve alignment information into CallArg.
  1840. if (isMemcpyEquivalentSpecialMember(D)) {
  1841. assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
  1842. const Expr *Arg = E->getArg(0);
  1843. LValue Src = EmitLValue(Arg);
  1844. QualType DestTy = getContext().getTypeDeclType(D->getParent());
  1845. LValue Dest = MakeAddrLValue(This, DestTy);
  1846. EmitAggregateCopyCtor(Dest, Src, ThisAVS.mayOverlap());
  1847. return;
  1848. }
  1849. // Add the rest of the user-supplied arguments.
  1850. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  1851. EvaluationOrder Order = E->isListInitialization()
  1852. ? EvaluationOrder::ForceLeftToRight
  1853. : EvaluationOrder::Default;
  1854. EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(),
  1855. /*ParamsToSkip*/ 0, Order);
  1856. EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args,
  1857. ThisAVS.mayOverlap(), E->getExprLoc(),
  1858. ThisAVS.isSanitizerChecked());
  1859. }
  1860. static bool canEmitDelegateCallArgs(CodeGenFunction &CGF,
  1861. const CXXConstructorDecl *Ctor,
  1862. CXXCtorType Type, CallArgList &Args) {
  1863. // We can't forward a variadic call.
  1864. if (Ctor->isVariadic())
  1865. return false;
  1866. if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1867. // If the parameters are callee-cleanup, it's not safe to forward.
  1868. for (auto *P : Ctor->parameters())
  1869. if (P->needsDestruction(CGF.getContext()))
  1870. return false;
  1871. // Likewise if they're inalloca.
  1872. const CGFunctionInfo &Info =
  1873. CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0, 0);
  1874. if (Info.usesInAlloca())
  1875. return false;
  1876. }
  1877. // Anything else should be OK.
  1878. return true;
  1879. }
  1880. void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
  1881. CXXCtorType Type,
  1882. bool ForVirtualBase,
  1883. bool Delegating,
  1884. Address This,
  1885. CallArgList &Args,
  1886. AggValueSlot::Overlap_t Overlap,
  1887. SourceLocation Loc,
  1888. bool NewPointerIsChecked) {
  1889. const CXXRecordDecl *ClassDecl = D->getParent();
  1890. if (!NewPointerIsChecked)
  1891. EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, Loc, This.getPointer(),
  1892. getContext().getRecordType(ClassDecl), CharUnits::Zero());
  1893. if (D->isTrivial() && D->isDefaultConstructor()) {
  1894. assert(Args.size() == 1 && "trivial default ctor with args");
  1895. return;
  1896. }
  1897. // If this is a trivial constructor, just emit what's needed. If this is a
  1898. // union copy constructor, we must emit a memcpy, because the AST does not
  1899. // model that copy.
  1900. if (isMemcpyEquivalentSpecialMember(D)) {
  1901. assert(Args.size() == 2 && "unexpected argcount for trivial ctor");
  1902. QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType();
  1903. Address Src = Address(Args[1].getRValue(*this).getScalarVal(), ConvertTypeForMem(SrcTy),
  1904. CGM.getNaturalTypeAlignment(SrcTy));
  1905. LValue SrcLVal = MakeAddrLValue(Src, SrcTy);
  1906. QualType DestTy = getContext().getTypeDeclType(ClassDecl);
  1907. LValue DestLVal = MakeAddrLValue(This, DestTy);
  1908. EmitAggregateCopyCtor(DestLVal, SrcLVal, Overlap);
  1909. return;
  1910. }
  1911. bool PassPrototypeArgs = true;
  1912. // Check whether we can actually emit the constructor before trying to do so.
  1913. if (auto Inherited = D->getInheritedConstructor()) {
  1914. PassPrototypeArgs = getTypes().inheritingCtorHasParams(Inherited, Type);
  1915. if (PassPrototypeArgs && !canEmitDelegateCallArgs(*this, D, Type, Args)) {
  1916. EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase,
  1917. Delegating, Args);
  1918. return;
  1919. }
  1920. }
  1921. // Insert any ABI-specific implicit constructor arguments.
  1922. CGCXXABI::AddedStructorArgCounts ExtraArgs =
  1923. CGM.getCXXABI().addImplicitConstructorArgs(*this, D, Type, ForVirtualBase,
  1924. Delegating, Args);
  1925. // Emit the call.
  1926. llvm::Constant *CalleePtr = CGM.getAddrOfCXXStructor(GlobalDecl(D, Type));
  1927. const CGFunctionInfo &Info = CGM.getTypes().arrangeCXXConstructorCall(
  1928. Args, D, Type, ExtraArgs.Prefix, ExtraArgs.Suffix, PassPrototypeArgs);
  1929. CGCallee Callee = CGCallee::forDirect(CalleePtr, GlobalDecl(D, Type));
  1930. EmitCall(Info, Callee, ReturnValueSlot(), Args, nullptr, false, Loc);
  1931. // Generate vtable assumptions if we're constructing a complete object
  1932. // with a vtable. We don't do this for base subobjects for two reasons:
  1933. // first, it's incorrect for classes with virtual bases, and second, we're
  1934. // about to overwrite the vptrs anyway.
  1935. // We also have to make sure if we can refer to vtable:
  1936. // - Otherwise we can refer to vtable if it's safe to speculatively emit.
  1937. // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are
  1938. // sure that definition of vtable is not hidden,
  1939. // then we are always safe to refer to it.
  1940. // FIXME: It looks like InstCombine is very inefficient on dealing with
  1941. // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily.
  1942. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  1943. ClassDecl->isDynamicClass() && Type != Ctor_Base &&
  1944. CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) &&
  1945. CGM.getCodeGenOpts().StrictVTablePointers)
  1946. EmitVTableAssumptionLoads(ClassDecl, This);
  1947. }
  1948. void CodeGenFunction::EmitInheritedCXXConstructorCall(
  1949. const CXXConstructorDecl *D, bool ForVirtualBase, Address This,
  1950. bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) {
  1951. CallArgList Args;
  1952. CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType());
  1953. // Forward the parameters.
  1954. if (InheritedFromVBase &&
  1955. CGM.getTarget().getCXXABI().hasConstructorVariants()) {
  1956. // Nothing to do; this construction is not responsible for constructing
  1957. // the base class containing the inherited constructor.
  1958. // FIXME: Can we just pass undef's for the remaining arguments if we don't
  1959. // have constructor variants?
  1960. Args.push_back(ThisArg);
  1961. } else if (!CXXInheritedCtorInitExprArgs.empty()) {
  1962. // The inheriting constructor was inlined; just inject its arguments.
  1963. assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() &&
  1964. "wrong number of parameters for inherited constructor call");
  1965. Args = CXXInheritedCtorInitExprArgs;
  1966. Args[0] = ThisArg;
  1967. } else {
  1968. // The inheriting constructor was not inlined. Emit delegating arguments.
  1969. Args.push_back(ThisArg);
  1970. const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl);
  1971. assert(OuterCtor->getNumParams() == D->getNumParams());
  1972. assert(!OuterCtor->isVariadic() && "should have been inlined");
  1973. for (const auto *Param : OuterCtor->parameters()) {
  1974. assert(getContext().hasSameUnqualifiedType(
  1975. OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(),
  1976. Param->getType()));
  1977. EmitDelegateCallArg(Args, Param, E->getLocation());
  1978. // Forward __attribute__(pass_object_size).
  1979. if (Param->hasAttr<PassObjectSizeAttr>()) {
  1980. auto *POSParam = SizeArguments[Param];
  1981. assert(POSParam && "missing pass_object_size value for forwarding");
  1982. EmitDelegateCallArg(Args, POSParam, E->getLocation());
  1983. }
  1984. }
  1985. }
  1986. EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false,
  1987. This, Args, AggValueSlot::MayOverlap,
  1988. E->getLocation(), /*NewPointerIsChecked*/true);
  1989. }
  1990. void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall(
  1991. const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase,
  1992. bool Delegating, CallArgList &Args) {
  1993. GlobalDecl GD(Ctor, CtorType);
  1994. InlinedInheritingConstructorScope Scope(*this, GD);
  1995. ApplyInlineDebugLocation DebugScope(*this, GD);
  1996. RunCleanupsScope RunCleanups(*this);
  1997. // Save the arguments to be passed to the inherited constructor.
  1998. CXXInheritedCtorInitExprArgs = Args;
  1999. FunctionArgList Params;
  2000. QualType RetType = BuildFunctionArgList(CurGD, Params);
  2001. FnRetTy = RetType;
  2002. // Insert any ABI-specific implicit constructor arguments.
  2003. CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType,
  2004. ForVirtualBase, Delegating, Args);
  2005. // Emit a simplified prolog. We only need to emit the implicit params.
  2006. assert(Args.size() >= Params.size() && "too few arguments for call");
  2007. for (unsigned I = 0, N = Args.size(); I != N; ++I) {
  2008. if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) {
  2009. const RValue &RV = Args[I].getRValue(*this);
  2010. assert(!RV.isComplex() && "complex indirect params not supported");
  2011. ParamValue Val = RV.isScalar()
  2012. ? ParamValue::forDirect(RV.getScalarVal())
  2013. : ParamValue::forIndirect(RV.getAggregateAddress());
  2014. EmitParmDecl(*Params[I], Val, I + 1);
  2015. }
  2016. }
  2017. // Create a return value slot if the ABI implementation wants one.
  2018. // FIXME: This is dumb, we should ask the ABI not to try to set the return
  2019. // value instead.
  2020. if (!RetType->isVoidType())
  2021. ReturnValue = CreateIRTemp(RetType, "retval.inhctor");
  2022. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  2023. CXXThisValue = CXXABIThisValue;
  2024. // Directly emit the constructor initializers.
  2025. EmitCtorPrologue(Ctor, CtorType, Params);
  2026. }
  2027. void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) {
  2028. llvm::Value *VTableGlobal =
  2029. CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass);
  2030. if (!VTableGlobal)
  2031. return;
  2032. // We can just use the base offset in the complete class.
  2033. CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset();
  2034. if (!NonVirtualOffset.isZero())
  2035. This =
  2036. ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr,
  2037. Vptr.VTableClass, Vptr.NearestVBase);
  2038. llvm::Value *VPtrValue =
  2039. GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass);
  2040. llvm::Value *Cmp =
  2041. Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables");
  2042. Builder.CreateAssumption(Cmp);
  2043. }
  2044. void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl,
  2045. Address This) {
  2046. if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl))
  2047. for (const VPtr &Vptr : getVTablePointers(ClassDecl))
  2048. EmitVTableAssumptionLoad(Vptr, This);
  2049. }
  2050. void
  2051. CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  2052. Address This, Address Src,
  2053. const CXXConstructExpr *E) {
  2054. const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
  2055. CallArgList Args;
  2056. // Push the this ptr.
  2057. Args.add(RValue::get(This.getPointer()), D->getThisType());
  2058. // Push the src ptr.
  2059. QualType QT = *(FPT->param_type_begin());
  2060. llvm::Type *t = CGM.getTypes().ConvertType(QT);
  2061. llvm::Value *SrcVal = Builder.CreateBitCast(Src.getPointer(), t);
  2062. Args.add(RValue::get(SrcVal), QT);
  2063. // Skip over first argument (Src).
  2064. EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
  2065. /*ParamsToSkip*/ 1);
  2066. EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase*/false,
  2067. /*Delegating*/false, This, Args,
  2068. AggValueSlot::MayOverlap, E->getExprLoc(),
  2069. /*NewPointerIsChecked*/false);
  2070. }
  2071. void
  2072. CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2073. CXXCtorType CtorType,
  2074. const FunctionArgList &Args,
  2075. SourceLocation Loc) {
  2076. CallArgList DelegateArgs;
  2077. FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
  2078. assert(I != E && "no parameters to constructor");
  2079. // this
  2080. Address This = LoadCXXThisAddress();
  2081. DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType());
  2082. ++I;
  2083. // FIXME: The location of the VTT parameter in the parameter list is
  2084. // specific to the Itanium ABI and shouldn't be hardcoded here.
  2085. if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
  2086. assert(I != E && "cannot skip vtt parameter, already done with args");
  2087. assert((*I)->getType()->isPointerType() &&
  2088. "skipping parameter not of vtt type");
  2089. ++I;
  2090. }
  2091. // Explicit arguments.
  2092. for (; I != E; ++I) {
  2093. const VarDecl *param = *I;
  2094. // FIXME: per-argument source location
  2095. EmitDelegateCallArg(DelegateArgs, param, Loc);
  2096. }
  2097. EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false,
  2098. /*Delegating=*/true, This, DelegateArgs,
  2099. AggValueSlot::MayOverlap, Loc,
  2100. /*NewPointerIsChecked=*/true);
  2101. }
  2102. namespace {
  2103. struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
  2104. const CXXDestructorDecl *Dtor;
  2105. Address Addr;
  2106. CXXDtorType Type;
  2107. CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr,
  2108. CXXDtorType Type)
  2109. : Dtor(D), Addr(Addr), Type(Type) {}
  2110. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2111. // We are calling the destructor from within the constructor.
  2112. // Therefore, "this" should have the expected type.
  2113. QualType ThisTy = Dtor->getThisObjectType();
  2114. CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
  2115. /*Delegating=*/true, Addr, ThisTy);
  2116. }
  2117. };
  2118. } // end anonymous namespace
  2119. void
  2120. CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  2121. const FunctionArgList &Args) {
  2122. assert(Ctor->isDelegatingConstructor());
  2123. Address ThisPtr = LoadCXXThisAddress();
  2124. AggValueSlot AggSlot =
  2125. AggValueSlot::forAddr(ThisPtr, Qualifiers(),
  2126. AggValueSlot::IsDestructed,
  2127. AggValueSlot::DoesNotNeedGCBarriers,
  2128. AggValueSlot::IsNotAliased,
  2129. AggValueSlot::MayOverlap,
  2130. AggValueSlot::IsNotZeroed,
  2131. // Checks are made by the code that calls constructor.
  2132. AggValueSlot::IsSanitizerChecked);
  2133. EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
  2134. const CXXRecordDecl *ClassDecl = Ctor->getParent();
  2135. if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
  2136. CXXDtorType Type =
  2137. CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
  2138. EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
  2139. ClassDecl->getDestructor(),
  2140. ThisPtr, Type);
  2141. }
  2142. }
  2143. void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
  2144. CXXDtorType Type,
  2145. bool ForVirtualBase,
  2146. bool Delegating, Address This,
  2147. QualType ThisTy) {
  2148. CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
  2149. Delegating, This, ThisTy);
  2150. }
  2151. namespace {
  2152. struct CallLocalDtor final : EHScopeStack::Cleanup {
  2153. const CXXDestructorDecl *Dtor;
  2154. Address Addr;
  2155. QualType Ty;
  2156. CallLocalDtor(const CXXDestructorDecl *D, Address Addr, QualType Ty)
  2157. : Dtor(D), Addr(Addr), Ty(Ty) {}
  2158. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2159. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  2160. /*ForVirtualBase=*/false,
  2161. /*Delegating=*/false, Addr, Ty);
  2162. }
  2163. };
  2164. } // end anonymous namespace
  2165. void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
  2166. QualType T, Address Addr) {
  2167. EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr, T);
  2168. }
  2169. void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) {
  2170. CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
  2171. if (!ClassDecl) return;
  2172. if (ClassDecl->hasTrivialDestructor()) return;
  2173. const CXXDestructorDecl *D = ClassDecl->getDestructor();
  2174. assert(D && D->isUsed() && "destructor not marked as used!");
  2175. PushDestructorCleanup(D, T, Addr);
  2176. }
  2177. void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) {
  2178. // Compute the address point.
  2179. llvm::Value *VTableAddressPoint =
  2180. CGM.getCXXABI().getVTableAddressPointInStructor(
  2181. *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase);
  2182. if (!VTableAddressPoint)
  2183. return;
  2184. // Compute where to store the address point.
  2185. llvm::Value *VirtualOffset = nullptr;
  2186. CharUnits NonVirtualOffset = CharUnits::Zero();
  2187. if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) {
  2188. // We need to use the virtual base offset offset because the virtual base
  2189. // might have a different offset in the most derived class.
  2190. VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(
  2191. *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase);
  2192. NonVirtualOffset = Vptr.OffsetFromNearestVBase;
  2193. } else {
  2194. // We can just use the base offset in the complete class.
  2195. NonVirtualOffset = Vptr.Base.getBaseOffset();
  2196. }
  2197. // Apply the offsets.
  2198. Address VTableField = LoadCXXThisAddress();
  2199. if (!NonVirtualOffset.isZero() || VirtualOffset)
  2200. VTableField = ApplyNonVirtualAndVirtualOffset(
  2201. *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass,
  2202. Vptr.NearestVBase);
  2203. // Finally, store the address point. Use the same LLVM types as the field to
  2204. // support optimization.
  2205. unsigned GlobalsAS = CGM.getDataLayout().getDefaultGlobalsAddressSpace();
  2206. unsigned ProgAS = CGM.getDataLayout().getProgramAddressSpace();
  2207. llvm::Type *VTablePtrTy =
  2208. llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
  2209. ->getPointerTo(ProgAS)
  2210. ->getPointerTo(GlobalsAS);
  2211. // vtable field is derived from `this` pointer, therefore they should be in
  2212. // the same addr space. Note that this might not be LLVM address space 0.
  2213. VTableField = Builder.CreateElementBitCast(VTableField, VTablePtrTy);
  2214. VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
  2215. llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
  2216. TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTablePtrTy);
  2217. CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
  2218. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2219. CGM.getCodeGenOpts().StrictVTablePointers)
  2220. CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass);
  2221. }
  2222. CodeGenFunction::VPtrsVector
  2223. CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) {
  2224. CodeGenFunction::VPtrsVector VPtrsResult;
  2225. VisitedVirtualBasesSetTy VBases;
  2226. getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()),
  2227. /*NearestVBase=*/nullptr,
  2228. /*OffsetFromNearestVBase=*/CharUnits::Zero(),
  2229. /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases,
  2230. VPtrsResult);
  2231. return VPtrsResult;
  2232. }
  2233. void CodeGenFunction::getVTablePointers(BaseSubobject Base,
  2234. const CXXRecordDecl *NearestVBase,
  2235. CharUnits OffsetFromNearestVBase,
  2236. bool BaseIsNonVirtualPrimaryBase,
  2237. const CXXRecordDecl *VTableClass,
  2238. VisitedVirtualBasesSetTy &VBases,
  2239. VPtrsVector &Vptrs) {
  2240. // If this base is a non-virtual primary base the address point has already
  2241. // been set.
  2242. if (!BaseIsNonVirtualPrimaryBase) {
  2243. // Initialize the vtable pointer for this base.
  2244. VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass};
  2245. Vptrs.push_back(Vptr);
  2246. }
  2247. const CXXRecordDecl *RD = Base.getBase();
  2248. // Traverse bases.
  2249. for (const auto &I : RD->bases()) {
  2250. auto *BaseDecl =
  2251. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  2252. // Ignore classes without a vtable.
  2253. if (!BaseDecl->isDynamicClass())
  2254. continue;
  2255. CharUnits BaseOffset;
  2256. CharUnits BaseOffsetFromNearestVBase;
  2257. bool BaseDeclIsNonVirtualPrimaryBase;
  2258. if (I.isVirtual()) {
  2259. // Check if we've visited this virtual base before.
  2260. if (!VBases.insert(BaseDecl).second)
  2261. continue;
  2262. const ASTRecordLayout &Layout =
  2263. getContext().getASTRecordLayout(VTableClass);
  2264. BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
  2265. BaseOffsetFromNearestVBase = CharUnits::Zero();
  2266. BaseDeclIsNonVirtualPrimaryBase = false;
  2267. } else {
  2268. const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
  2269. BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
  2270. BaseOffsetFromNearestVBase =
  2271. OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
  2272. BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
  2273. }
  2274. getVTablePointers(
  2275. BaseSubobject(BaseDecl, BaseOffset),
  2276. I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase,
  2277. BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs);
  2278. }
  2279. }
  2280. void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
  2281. // Ignore classes without a vtable.
  2282. if (!RD->isDynamicClass())
  2283. return;
  2284. // Initialize the vtable pointers for this class and all of its bases.
  2285. if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD))
  2286. for (const VPtr &Vptr : getVTablePointers(RD))
  2287. InitializeVTablePointer(Vptr);
  2288. if (RD->getNumVBases())
  2289. CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
  2290. }
  2291. llvm::Value *CodeGenFunction::GetVTablePtr(Address This,
  2292. llvm::Type *VTableTy,
  2293. const CXXRecordDecl *RD) {
  2294. Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy);
  2295. llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
  2296. TBAAAccessInfo TBAAInfo = CGM.getTBAAVTablePtrAccessInfo(VTableTy);
  2297. CGM.DecorateInstructionWithTBAA(VTable, TBAAInfo);
  2298. if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
  2299. CGM.getCodeGenOpts().StrictVTablePointers)
  2300. CGM.DecorateInstructionWithInvariantGroup(VTable, RD);
  2301. return VTable;
  2302. }
  2303. // If a class has a single non-virtual base and does not introduce or override
  2304. // virtual member functions or fields, it will have the same layout as its base.
  2305. // This function returns the least derived such class.
  2306. //
  2307. // Casting an instance of a base class to such a derived class is technically
  2308. // undefined behavior, but it is a relatively common hack for introducing member
  2309. // functions on class instances with specific properties (e.g. llvm::Operator)
  2310. // that works under most compilers and should not have security implications, so
  2311. // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
  2312. static const CXXRecordDecl *
  2313. LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
  2314. if (!RD->field_empty())
  2315. return RD;
  2316. if (RD->getNumVBases() != 0)
  2317. return RD;
  2318. if (RD->getNumBases() != 1)
  2319. return RD;
  2320. for (const CXXMethodDecl *MD : RD->methods()) {
  2321. if (MD->isVirtual()) {
  2322. // Virtual member functions are only ok if they are implicit destructors
  2323. // because the implicit destructor will have the same semantics as the
  2324. // base class's destructor if no fields are added.
  2325. if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
  2326. continue;
  2327. return RD;
  2328. }
  2329. }
  2330. return LeastDerivedClassWithSameLayout(
  2331. RD->bases_begin()->getType()->getAsCXXRecordDecl());
  2332. }
  2333. void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD,
  2334. llvm::Value *VTable,
  2335. SourceLocation Loc) {
  2336. if (SanOpts.has(SanitizerKind::CFIVCall))
  2337. EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc);
  2338. else if (CGM.getCodeGenOpts().WholeProgramVTables &&
  2339. // Don't insert type test assumes if we are forcing public
  2340. // visibility.
  2341. !CGM.AlwaysHasLTOVisibilityPublic(RD)) {
  2342. QualType Ty = QualType(RD->getTypeForDecl(), 0);
  2343. llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(Ty);
  2344. llvm::Value *TypeId =
  2345. llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
  2346. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2347. // If we already know that the call has hidden LTO visibility, emit
  2348. // @llvm.type.test(). Otherwise emit @llvm.public.type.test(), which WPD
  2349. // will convert to @llvm.type.test() if we assert at link time that we have
  2350. // whole program visibility.
  2351. llvm::Intrinsic::ID IID = CGM.HasHiddenLTOVisibility(RD)
  2352. ? llvm::Intrinsic::type_test
  2353. : llvm::Intrinsic::public_type_test;
  2354. llvm::Value *TypeTest =
  2355. Builder.CreateCall(CGM.getIntrinsic(IID), {CastedVTable, TypeId});
  2356. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest);
  2357. }
  2358. }
  2359. void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD,
  2360. llvm::Value *VTable,
  2361. CFITypeCheckKind TCK,
  2362. SourceLocation Loc) {
  2363. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2364. RD = LeastDerivedClassWithSameLayout(RD);
  2365. EmitVTablePtrCheck(RD, VTable, TCK, Loc);
  2366. }
  2367. void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T, Address Derived,
  2368. bool MayBeNull,
  2369. CFITypeCheckKind TCK,
  2370. SourceLocation Loc) {
  2371. if (!getLangOpts().CPlusPlus)
  2372. return;
  2373. auto *ClassTy = T->getAs<RecordType>();
  2374. if (!ClassTy)
  2375. return;
  2376. const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
  2377. if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
  2378. return;
  2379. if (!SanOpts.has(SanitizerKind::CFICastStrict))
  2380. ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
  2381. llvm::BasicBlock *ContBlock = nullptr;
  2382. if (MayBeNull) {
  2383. llvm::Value *DerivedNotNull =
  2384. Builder.CreateIsNotNull(Derived.getPointer(), "cast.nonnull");
  2385. llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
  2386. ContBlock = createBasicBlock("cast.cont");
  2387. Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
  2388. EmitBlock(CheckBlock);
  2389. }
  2390. llvm::Value *VTable;
  2391. std::tie(VTable, ClassDecl) =
  2392. CGM.getCXXABI().LoadVTablePtr(*this, Derived, ClassDecl);
  2393. EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
  2394. if (MayBeNull) {
  2395. Builder.CreateBr(ContBlock);
  2396. EmitBlock(ContBlock);
  2397. }
  2398. }
  2399. void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
  2400. llvm::Value *VTable,
  2401. CFITypeCheckKind TCK,
  2402. SourceLocation Loc) {
  2403. if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso &&
  2404. !CGM.HasHiddenLTOVisibility(RD))
  2405. return;
  2406. SanitizerMask M;
  2407. llvm::SanitizerStatKind SSK;
  2408. switch (TCK) {
  2409. case CFITCK_VCall:
  2410. M = SanitizerKind::CFIVCall;
  2411. SSK = llvm::SanStat_CFI_VCall;
  2412. break;
  2413. case CFITCK_NVCall:
  2414. M = SanitizerKind::CFINVCall;
  2415. SSK = llvm::SanStat_CFI_NVCall;
  2416. break;
  2417. case CFITCK_DerivedCast:
  2418. M = SanitizerKind::CFIDerivedCast;
  2419. SSK = llvm::SanStat_CFI_DerivedCast;
  2420. break;
  2421. case CFITCK_UnrelatedCast:
  2422. M = SanitizerKind::CFIUnrelatedCast;
  2423. SSK = llvm::SanStat_CFI_UnrelatedCast;
  2424. break;
  2425. case CFITCK_ICall:
  2426. case CFITCK_NVMFCall:
  2427. case CFITCK_VMFCall:
  2428. llvm_unreachable("unexpected sanitizer kind");
  2429. }
  2430. std::string TypeName = RD->getQualifiedNameAsString();
  2431. if (getContext().getNoSanitizeList().containsType(M, TypeName))
  2432. return;
  2433. SanitizerScope SanScope(this);
  2434. EmitSanitizerStatReport(SSK);
  2435. llvm::Metadata *MD =
  2436. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2437. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  2438. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2439. llvm::Value *TypeTest = Builder.CreateCall(
  2440. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId});
  2441. llvm::Constant *StaticData[] = {
  2442. llvm::ConstantInt::get(Int8Ty, TCK),
  2443. EmitCheckSourceLocation(Loc),
  2444. EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
  2445. };
  2446. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  2447. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  2448. EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData);
  2449. return;
  2450. }
  2451. if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) {
  2452. EmitTrapCheck(TypeTest, SanitizerHandler::CFICheckFail);
  2453. return;
  2454. }
  2455. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  2456. CGM.getLLVMContext(),
  2457. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  2458. llvm::Value *ValidVtable = Builder.CreateCall(
  2459. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables});
  2460. EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail,
  2461. StaticData, {CastedVTable, ValidVtable});
  2462. }
  2463. bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) {
  2464. if (!CGM.getCodeGenOpts().WholeProgramVTables ||
  2465. !CGM.HasHiddenLTOVisibility(RD))
  2466. return false;
  2467. if (CGM.getCodeGenOpts().VirtualFunctionElimination)
  2468. return true;
  2469. if (!SanOpts.has(SanitizerKind::CFIVCall) ||
  2470. !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall))
  2471. return false;
  2472. std::string TypeName = RD->getQualifiedNameAsString();
  2473. return !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall,
  2474. TypeName);
  2475. }
  2476. llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad(
  2477. const CXXRecordDecl *RD, llvm::Value *VTable, llvm::Type *VTableTy,
  2478. uint64_t VTableByteOffset) {
  2479. SanitizerScope SanScope(this);
  2480. EmitSanitizerStatReport(llvm::SanStat_CFI_VCall);
  2481. llvm::Metadata *MD =
  2482. CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  2483. llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD);
  2484. llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
  2485. llvm::Value *CheckedLoad = Builder.CreateCall(
  2486. CGM.getIntrinsic(llvm::Intrinsic::type_checked_load),
  2487. {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset),
  2488. TypeId});
  2489. llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1);
  2490. std::string TypeName = RD->getQualifiedNameAsString();
  2491. if (SanOpts.has(SanitizerKind::CFIVCall) &&
  2492. !getContext().getNoSanitizeList().containsType(SanitizerKind::CFIVCall,
  2493. TypeName)) {
  2494. EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall),
  2495. SanitizerHandler::CFICheckFail, {}, {});
  2496. }
  2497. return Builder.CreateBitCast(Builder.CreateExtractValue(CheckedLoad, 0),
  2498. VTableTy);
  2499. }
  2500. void CodeGenFunction::EmitForwardingCallToLambda(
  2501. const CXXMethodDecl *callOperator,
  2502. CallArgList &callArgs) {
  2503. // Get the address of the call operator.
  2504. const CGFunctionInfo &calleeFnInfo =
  2505. CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
  2506. llvm::Constant *calleePtr =
  2507. CGM.GetAddrOfFunction(GlobalDecl(callOperator),
  2508. CGM.getTypes().GetFunctionType(calleeFnInfo));
  2509. // Prepare the return slot.
  2510. const FunctionProtoType *FPT =
  2511. callOperator->getType()->castAs<FunctionProtoType>();
  2512. QualType resultType = FPT->getReturnType();
  2513. ReturnValueSlot returnSlot;
  2514. if (!resultType->isVoidType() &&
  2515. calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  2516. !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
  2517. returnSlot =
  2518. ReturnValueSlot(ReturnValue, resultType.isVolatileQualified(),
  2519. /*IsUnused=*/false, /*IsExternallyDestructed=*/true);
  2520. // We don't need to separately arrange the call arguments because
  2521. // the call can't be variadic anyway --- it's impossible to forward
  2522. // variadic arguments.
  2523. // Now emit our call.
  2524. auto callee = CGCallee::forDirect(calleePtr, GlobalDecl(callOperator));
  2525. RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs);
  2526. // If necessary, copy the returned value into the slot.
  2527. if (!resultType->isVoidType() && returnSlot.isNull()) {
  2528. if (getLangOpts().ObjCAutoRefCount && resultType->isObjCRetainableType()) {
  2529. RV = RValue::get(EmitARCRetainAutoreleasedReturnValue(RV.getScalarVal()));
  2530. }
  2531. EmitReturnOfRValue(RV, resultType);
  2532. } else
  2533. EmitBranchThroughCleanup(ReturnBlock);
  2534. }
  2535. void CodeGenFunction::EmitLambdaBlockInvokeBody() {
  2536. const BlockDecl *BD = BlockInfo->getBlockDecl();
  2537. const VarDecl *variable = BD->capture_begin()->getVariable();
  2538. const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
  2539. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2540. if (CallOp->isVariadic()) {
  2541. // FIXME: Making this work correctly is nasty because it requires either
  2542. // cloning the body of the call operator or making the call operator
  2543. // forward.
  2544. CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
  2545. return;
  2546. }
  2547. // Start building arguments for forwarding call
  2548. CallArgList CallArgs;
  2549. QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
  2550. Address ThisPtr = GetAddrOfBlockDecl(variable);
  2551. CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
  2552. // Add the rest of the parameters.
  2553. for (auto *param : BD->parameters())
  2554. EmitDelegateCallArg(CallArgs, param, param->getBeginLoc());
  2555. assert(!Lambda->isGenericLambda() &&
  2556. "generic lambda interconversion to block not implemented");
  2557. EmitForwardingCallToLambda(CallOp, CallArgs);
  2558. }
  2559. void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
  2560. const CXXRecordDecl *Lambda = MD->getParent();
  2561. // Start building arguments for forwarding call
  2562. CallArgList CallArgs;
  2563. QualType LambdaType = getContext().getRecordType(Lambda);
  2564. QualType ThisType = getContext().getPointerType(LambdaType);
  2565. Address ThisPtr = CreateMemTemp(LambdaType, "unused.capture");
  2566. CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType);
  2567. // Add the rest of the parameters.
  2568. for (auto *Param : MD->parameters())
  2569. EmitDelegateCallArg(CallArgs, Param, Param->getBeginLoc());
  2570. const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
  2571. // For a generic lambda, find the corresponding call operator specialization
  2572. // to which the call to the static-invoker shall be forwarded.
  2573. if (Lambda->isGenericLambda()) {
  2574. assert(MD->isFunctionTemplateSpecialization());
  2575. const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
  2576. FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
  2577. void *InsertPos = nullptr;
  2578. FunctionDecl *CorrespondingCallOpSpecialization =
  2579. CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
  2580. assert(CorrespondingCallOpSpecialization);
  2581. CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
  2582. }
  2583. EmitForwardingCallToLambda(CallOp, CallArgs);
  2584. }
  2585. void CodeGenFunction::EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD) {
  2586. if (MD->isVariadic()) {
  2587. // FIXME: Making this work correctly is nasty because it requires either
  2588. // cloning the body of the call operator or making the call operator forward.
  2589. CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
  2590. return;
  2591. }
  2592. EmitLambdaDelegatingInvokeBody(MD);
  2593. }