CGDecl.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Decl nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGBlocks.h"
  14. #include "CGCXXABI.h"
  15. #include "CGCleanup.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGOpenCLRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenFunction.h"
  20. #include "CodeGenModule.h"
  21. #include "ConstantEmitter.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/CharUnits.h"
  25. #include "clang/AST/Decl.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclOpenMP.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/CodeGen/CGFunctionInfo.h"
  31. #include "clang/Frontend/CodeGenOptions.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/GlobalVariable.h"
  34. #include "llvm/IR/Intrinsics.h"
  35. #include "llvm/IR/Type.h"
  36. using namespace clang;
  37. using namespace CodeGen;
  38. void CodeGenFunction::EmitDecl(const Decl &D) {
  39. switch (D.getKind()) {
  40. case Decl::BuiltinTemplate:
  41. case Decl::TranslationUnit:
  42. case Decl::ExternCContext:
  43. case Decl::Namespace:
  44. case Decl::UnresolvedUsingTypename:
  45. case Decl::ClassTemplateSpecialization:
  46. case Decl::ClassTemplatePartialSpecialization:
  47. case Decl::VarTemplateSpecialization:
  48. case Decl::VarTemplatePartialSpecialization:
  49. case Decl::TemplateTypeParm:
  50. case Decl::UnresolvedUsingValue:
  51. case Decl::NonTypeTemplateParm:
  52. case Decl::CXXDeductionGuide:
  53. case Decl::CXXMethod:
  54. case Decl::CXXConstructor:
  55. case Decl::CXXDestructor:
  56. case Decl::CXXConversion:
  57. case Decl::Field:
  58. case Decl::MSProperty:
  59. case Decl::IndirectField:
  60. case Decl::ObjCIvar:
  61. case Decl::ObjCAtDefsField:
  62. case Decl::ParmVar:
  63. case Decl::ImplicitParam:
  64. case Decl::ClassTemplate:
  65. case Decl::VarTemplate:
  66. case Decl::FunctionTemplate:
  67. case Decl::TypeAliasTemplate:
  68. case Decl::TemplateTemplateParm:
  69. case Decl::ObjCMethod:
  70. case Decl::ObjCCategory:
  71. case Decl::ObjCProtocol:
  72. case Decl::ObjCInterface:
  73. case Decl::ObjCCategoryImpl:
  74. case Decl::ObjCImplementation:
  75. case Decl::ObjCProperty:
  76. case Decl::ObjCCompatibleAlias:
  77. case Decl::PragmaComment:
  78. case Decl::PragmaDetectMismatch:
  79. case Decl::AccessSpec:
  80. case Decl::LinkageSpec:
  81. case Decl::Export:
  82. case Decl::ObjCPropertyImpl:
  83. case Decl::FileScopeAsm:
  84. case Decl::Friend:
  85. case Decl::FriendTemplate:
  86. case Decl::Block:
  87. case Decl::Captured:
  88. case Decl::ClassScopeFunctionSpecialization:
  89. case Decl::UsingShadow:
  90. case Decl::ConstructorUsingShadow:
  91. case Decl::ObjCTypeParam:
  92. case Decl::Binding:
  93. llvm_unreachable("Declaration should not be in declstmts!");
  94. case Decl::Function: // void X();
  95. case Decl::Record: // struct/union/class X;
  96. case Decl::Enum: // enum X;
  97. case Decl::EnumConstant: // enum ? { X = ? }
  98. case Decl::CXXRecord: // struct/union/class X; [C++]
  99. case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
  100. case Decl::Label: // __label__ x;
  101. case Decl::Import:
  102. case Decl::OMPThreadPrivate:
  103. case Decl::OMPCapturedExpr:
  104. case Decl::Empty:
  105. // None of these decls require codegen support.
  106. return;
  107. case Decl::NamespaceAlias:
  108. if (CGDebugInfo *DI = getDebugInfo())
  109. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
  110. return;
  111. case Decl::Using: // using X; [C++]
  112. if (CGDebugInfo *DI = getDebugInfo())
  113. DI->EmitUsingDecl(cast<UsingDecl>(D));
  114. return;
  115. case Decl::UsingPack:
  116. for (auto *Using : cast<UsingPackDecl>(D).expansions())
  117. EmitDecl(*Using);
  118. return;
  119. case Decl::UsingDirective: // using namespace X; [C++]
  120. if (CGDebugInfo *DI = getDebugInfo())
  121. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
  122. return;
  123. case Decl::Var:
  124. case Decl::Decomposition: {
  125. const VarDecl &VD = cast<VarDecl>(D);
  126. assert(VD.isLocalVarDecl() &&
  127. "Should not see file-scope variables inside a function!");
  128. EmitVarDecl(VD);
  129. if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
  130. for (auto *B : DD->bindings())
  131. if (auto *HD = B->getHoldingVar())
  132. EmitVarDecl(*HD);
  133. return;
  134. }
  135. case Decl::OMPDeclareReduction:
  136. return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
  137. case Decl::Typedef: // typedef int X;
  138. case Decl::TypeAlias: { // using X = int; [C++0x]
  139. const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
  140. QualType Ty = TD.getUnderlyingType();
  141. if (Ty->isVariablyModifiedType())
  142. EmitVariablyModifiedType(Ty);
  143. }
  144. }
  145. }
  146. /// EmitVarDecl - This method handles emission of any variable declaration
  147. /// inside a function, including static vars etc.
  148. void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
  149. if (D.hasExternalStorage())
  150. // Don't emit it now, allow it to be emitted lazily on its first use.
  151. return;
  152. // Some function-scope variable does not have static storage but still
  153. // needs to be emitted like a static variable, e.g. a function-scope
  154. // variable in constant address space in OpenCL.
  155. if (D.getStorageDuration() != SD_Automatic) {
  156. // Static sampler variables translated to function calls.
  157. if (D.getType()->isSamplerT())
  158. return;
  159. llvm::GlobalValue::LinkageTypes Linkage =
  160. CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
  161. // FIXME: We need to force the emission/use of a guard variable for
  162. // some variables even if we can constant-evaluate them because
  163. // we can't guarantee every translation unit will constant-evaluate them.
  164. return EmitStaticVarDecl(D, Linkage);
  165. }
  166. if (D.getType().getAddressSpace() == LangAS::opencl_local)
  167. return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
  168. assert(D.hasLocalStorage());
  169. return EmitAutoVarDecl(D);
  170. }
  171. static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
  172. if (CGM.getLangOpts().CPlusPlus)
  173. return CGM.getMangledName(&D).str();
  174. // If this isn't C++, we don't need a mangled name, just a pretty one.
  175. assert(!D.isExternallyVisible() && "name shouldn't matter");
  176. std::string ContextName;
  177. const DeclContext *DC = D.getDeclContext();
  178. if (auto *CD = dyn_cast<CapturedDecl>(DC))
  179. DC = cast<DeclContext>(CD->getNonClosureContext());
  180. if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  181. ContextName = CGM.getMangledName(FD);
  182. else if (const auto *BD = dyn_cast<BlockDecl>(DC))
  183. ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
  184. else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
  185. ContextName = OMD->getSelector().getAsString();
  186. else
  187. llvm_unreachable("Unknown context for static var decl");
  188. ContextName += "." + D.getNameAsString();
  189. return ContextName;
  190. }
  191. llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
  192. const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
  193. // In general, we don't always emit static var decls once before we reference
  194. // them. It is possible to reference them before emitting the function that
  195. // contains them, and it is possible to emit the containing function multiple
  196. // times.
  197. if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
  198. return ExistingGV;
  199. QualType Ty = D.getType();
  200. assert(Ty->isConstantSizeType() && "VLAs can't be static");
  201. // Use the label if the variable is renamed with the asm-label extension.
  202. std::string Name;
  203. if (D.hasAttr<AsmLabelAttr>())
  204. Name = getMangledName(&D);
  205. else
  206. Name = getStaticDeclName(*this, D);
  207. llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
  208. LangAS AS = GetGlobalVarAddressSpace(&D);
  209. unsigned TargetAS = getContext().getTargetAddressSpace(AS);
  210. // Local address space cannot have an initializer.
  211. llvm::Constant *Init = nullptr;
  212. if (Ty.getAddressSpace() != LangAS::opencl_local)
  213. Init = EmitNullConstant(Ty);
  214. else
  215. Init = llvm::UndefValue::get(LTy);
  216. llvm::GlobalVariable *GV = new llvm::GlobalVariable(
  217. getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
  218. nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  219. GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
  220. setGVProperties(GV, &D);
  221. if (supportsCOMDAT() && GV->isWeakForLinker())
  222. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  223. if (D.getTLSKind())
  224. setTLSMode(GV, D);
  225. if (D.isExternallyVisible()) {
  226. if (D.hasAttr<DLLImportAttr>())
  227. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  228. else if (D.hasAttr<DLLExportAttr>())
  229. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  230. }
  231. // Make sure the result is of the correct type.
  232. LangAS ExpectedAS = Ty.getAddressSpace();
  233. llvm::Constant *Addr = GV;
  234. if (AS != ExpectedAS) {
  235. Addr = getTargetCodeGenInfo().performAddrSpaceCast(
  236. *this, GV, AS, ExpectedAS,
  237. LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
  238. }
  239. setStaticLocalDeclAddress(&D, Addr);
  240. // Ensure that the static local gets initialized by making sure the parent
  241. // function gets emitted eventually.
  242. const Decl *DC = cast<Decl>(D.getDeclContext());
  243. // We can't name blocks or captured statements directly, so try to emit their
  244. // parents.
  245. if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
  246. DC = DC->getNonClosureContext();
  247. // FIXME: Ensure that global blocks get emitted.
  248. if (!DC)
  249. return Addr;
  250. }
  251. GlobalDecl GD;
  252. if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  253. GD = GlobalDecl(CD, Ctor_Base);
  254. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  255. GD = GlobalDecl(DD, Dtor_Base);
  256. else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
  257. GD = GlobalDecl(FD);
  258. else {
  259. // Don't do anything for Obj-C method decls or global closures. We should
  260. // never defer them.
  261. assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
  262. }
  263. if (GD.getDecl())
  264. (void)GetAddrOfGlobal(GD);
  265. return Addr;
  266. }
  267. /// hasNontrivialDestruction - Determine whether a type's destruction is
  268. /// non-trivial. If so, and the variable uses static initialization, we must
  269. /// register its destructor to run on exit.
  270. static bool hasNontrivialDestruction(QualType T) {
  271. CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  272. return RD && !RD->hasTrivialDestructor();
  273. }
  274. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  275. /// global variable that has already been created for it. If the initializer
  276. /// has a different type than GV does, this may free GV and return a different
  277. /// one. Otherwise it just returns GV.
  278. llvm::GlobalVariable *
  279. CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
  280. llvm::GlobalVariable *GV) {
  281. ConstantEmitter emitter(*this);
  282. llvm::Constant *Init = emitter.tryEmitForInitializer(D);
  283. // If constant emission failed, then this should be a C++ static
  284. // initializer.
  285. if (!Init) {
  286. if (!getLangOpts().CPlusPlus)
  287. CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
  288. else if (HaveInsertPoint()) {
  289. // Since we have a static initializer, this global variable can't
  290. // be constant.
  291. GV->setConstant(false);
  292. EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
  293. }
  294. return GV;
  295. }
  296. // The initializer may differ in type from the global. Rewrite
  297. // the global to match the initializer. (We have to do this
  298. // because some types, like unions, can't be completely represented
  299. // in the LLVM type system.)
  300. if (GV->getType()->getElementType() != Init->getType()) {
  301. llvm::GlobalVariable *OldGV = GV;
  302. GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
  303. OldGV->isConstant(),
  304. OldGV->getLinkage(), Init, "",
  305. /*InsertBefore*/ OldGV,
  306. OldGV->getThreadLocalMode(),
  307. CGM.getContext().getTargetAddressSpace(D.getType()));
  308. GV->setVisibility(OldGV->getVisibility());
  309. GV->setDSOLocal(OldGV->isDSOLocal());
  310. GV->setComdat(OldGV->getComdat());
  311. // Steal the name of the old global
  312. GV->takeName(OldGV);
  313. // Replace all uses of the old global with the new global
  314. llvm::Constant *NewPtrForOldDecl =
  315. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  316. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  317. // Erase the old global, since it is no longer used.
  318. OldGV->eraseFromParent();
  319. }
  320. GV->setConstant(CGM.isTypeConstant(D.getType(), true));
  321. GV->setInitializer(Init);
  322. emitter.finalize(GV);
  323. if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
  324. // We have a constant initializer, but a nontrivial destructor. We still
  325. // need to perform a guarded "initialization" in order to register the
  326. // destructor.
  327. EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
  328. }
  329. return GV;
  330. }
  331. void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
  332. llvm::GlobalValue::LinkageTypes Linkage) {
  333. // Check to see if we already have a global variable for this
  334. // declaration. This can happen when double-emitting function
  335. // bodies, e.g. with complete and base constructors.
  336. llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
  337. CharUnits alignment = getContext().getDeclAlign(&D);
  338. // Store into LocalDeclMap before generating initializer to handle
  339. // circular references.
  340. setAddrOfLocalVar(&D, Address(addr, alignment));
  341. // We can't have a VLA here, but we can have a pointer to a VLA,
  342. // even though that doesn't really make any sense.
  343. // Make sure to evaluate VLA bounds now so that we have them for later.
  344. if (D.getType()->isVariablyModifiedType())
  345. EmitVariablyModifiedType(D.getType());
  346. // Save the type in case adding the initializer forces a type change.
  347. llvm::Type *expectedType = addr->getType();
  348. llvm::GlobalVariable *var =
  349. cast<llvm::GlobalVariable>(addr->stripPointerCasts());
  350. // CUDA's local and local static __shared__ variables should not
  351. // have any non-empty initializers. This is ensured by Sema.
  352. // Whatever initializer such variable may have when it gets here is
  353. // a no-op and should not be emitted.
  354. bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  355. D.hasAttr<CUDASharedAttr>();
  356. // If this value has an initializer, emit it.
  357. if (D.getInit() && !isCudaSharedVar)
  358. var = AddInitializerToStaticVarDecl(D, var);
  359. var->setAlignment(alignment.getQuantity());
  360. if (D.hasAttr<AnnotateAttr>())
  361. CGM.AddGlobalAnnotations(&D, var);
  362. if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
  363. var->addAttribute("bss-section", SA->getName());
  364. if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
  365. var->addAttribute("data-section", SA->getName());
  366. if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
  367. var->addAttribute("rodata-section", SA->getName());
  368. if (const SectionAttr *SA = D.getAttr<SectionAttr>())
  369. var->setSection(SA->getName());
  370. if (D.hasAttr<UsedAttr>())
  371. CGM.addUsedGlobal(var);
  372. // We may have to cast the constant because of the initializer
  373. // mismatch above.
  374. //
  375. // FIXME: It is really dangerous to store this in the map; if anyone
  376. // RAUW's the GV uses of this constant will be invalid.
  377. llvm::Constant *castedAddr =
  378. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
  379. if (var != castedAddr)
  380. LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
  381. CGM.setStaticLocalDeclAddress(&D, castedAddr);
  382. CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
  383. // Emit global variable debug descriptor for static vars.
  384. CGDebugInfo *DI = getDebugInfo();
  385. if (DI &&
  386. CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
  387. DI->setLocation(D.getLocation());
  388. DI->EmitGlobalVariable(var, &D);
  389. }
  390. }
  391. namespace {
  392. struct DestroyObject final : EHScopeStack::Cleanup {
  393. DestroyObject(Address addr, QualType type,
  394. CodeGenFunction::Destroyer *destroyer,
  395. bool useEHCleanupForArray)
  396. : addr(addr), type(type), destroyer(destroyer),
  397. useEHCleanupForArray(useEHCleanupForArray) {}
  398. Address addr;
  399. QualType type;
  400. CodeGenFunction::Destroyer *destroyer;
  401. bool useEHCleanupForArray;
  402. void Emit(CodeGenFunction &CGF, Flags flags) override {
  403. // Don't use an EH cleanup recursively from an EH cleanup.
  404. bool useEHCleanupForArray =
  405. flags.isForNormalCleanup() && this->useEHCleanupForArray;
  406. CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
  407. }
  408. };
  409. struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
  410. DestroyNRVOVariable(Address addr,
  411. const CXXDestructorDecl *Dtor,
  412. llvm::Value *NRVOFlag)
  413. : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
  414. const CXXDestructorDecl *Dtor;
  415. llvm::Value *NRVOFlag;
  416. Address Loc;
  417. void Emit(CodeGenFunction &CGF, Flags flags) override {
  418. // Along the exceptions path we always execute the dtor.
  419. bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
  420. llvm::BasicBlock *SkipDtorBB = nullptr;
  421. if (NRVO) {
  422. // If we exited via NRVO, we skip the destructor call.
  423. llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
  424. SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
  425. llvm::Value *DidNRVO =
  426. CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
  427. CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
  428. CGF.EmitBlock(RunDtorBB);
  429. }
  430. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
  431. /*ForVirtualBase=*/false,
  432. /*Delegating=*/false,
  433. Loc);
  434. if (NRVO) CGF.EmitBlock(SkipDtorBB);
  435. }
  436. };
  437. struct CallStackRestore final : EHScopeStack::Cleanup {
  438. Address Stack;
  439. CallStackRestore(Address Stack) : Stack(Stack) {}
  440. void Emit(CodeGenFunction &CGF, Flags flags) override {
  441. llvm::Value *V = CGF.Builder.CreateLoad(Stack);
  442. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  443. CGF.Builder.CreateCall(F, V);
  444. }
  445. };
  446. struct ExtendGCLifetime final : EHScopeStack::Cleanup {
  447. const VarDecl &Var;
  448. ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
  449. void Emit(CodeGenFunction &CGF, Flags flags) override {
  450. // Compute the address of the local variable, in case it's a
  451. // byref or something.
  452. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  453. Var.getType(), VK_LValue, SourceLocation());
  454. llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
  455. SourceLocation());
  456. CGF.EmitExtendGCLifetime(value);
  457. }
  458. };
  459. struct CallCleanupFunction final : EHScopeStack::Cleanup {
  460. llvm::Constant *CleanupFn;
  461. const CGFunctionInfo &FnInfo;
  462. const VarDecl &Var;
  463. CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
  464. const VarDecl *Var)
  465. : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
  466. void Emit(CodeGenFunction &CGF, Flags flags) override {
  467. DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
  468. Var.getType(), VK_LValue, SourceLocation());
  469. // Compute the address of the local variable, in case it's a byref
  470. // or something.
  471. llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
  472. // In some cases, the type of the function argument will be different from
  473. // the type of the pointer. An example of this is
  474. // void f(void* arg);
  475. // __attribute__((cleanup(f))) void *g;
  476. //
  477. // To fix this we insert a bitcast here.
  478. QualType ArgTy = FnInfo.arg_begin()->type;
  479. llvm::Value *Arg =
  480. CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
  481. CallArgList Args;
  482. Args.add(RValue::get(Arg),
  483. CGF.getContext().getPointerType(Var.getType()));
  484. auto Callee = CGCallee::forDirect(CleanupFn);
  485. CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
  486. }
  487. };
  488. } // end anonymous namespace
  489. /// EmitAutoVarWithLifetime - Does the setup required for an automatic
  490. /// variable with lifetime.
  491. static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
  492. Address addr,
  493. Qualifiers::ObjCLifetime lifetime) {
  494. switch (lifetime) {
  495. case Qualifiers::OCL_None:
  496. llvm_unreachable("present but none");
  497. case Qualifiers::OCL_ExplicitNone:
  498. // nothing to do
  499. break;
  500. case Qualifiers::OCL_Strong: {
  501. CodeGenFunction::Destroyer *destroyer =
  502. (var.hasAttr<ObjCPreciseLifetimeAttr>()
  503. ? CodeGenFunction::destroyARCStrongPrecise
  504. : CodeGenFunction::destroyARCStrongImprecise);
  505. CleanupKind cleanupKind = CGF.getARCCleanupKind();
  506. CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
  507. cleanupKind & EHCleanup);
  508. break;
  509. }
  510. case Qualifiers::OCL_Autoreleasing:
  511. // nothing to do
  512. break;
  513. case Qualifiers::OCL_Weak:
  514. // __weak objects always get EH cleanups; otherwise, exceptions
  515. // could cause really nasty crashes instead of mere leaks.
  516. CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
  517. CodeGenFunction::destroyARCWeak,
  518. /*useEHCleanup*/ true);
  519. break;
  520. }
  521. }
  522. static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
  523. if (const Expr *e = dyn_cast<Expr>(s)) {
  524. // Skip the most common kinds of expressions that make
  525. // hierarchy-walking expensive.
  526. s = e = e->IgnoreParenCasts();
  527. if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
  528. return (ref->getDecl() == &var);
  529. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  530. const BlockDecl *block = be->getBlockDecl();
  531. for (const auto &I : block->captures()) {
  532. if (I.getVariable() == &var)
  533. return true;
  534. }
  535. }
  536. }
  537. for (const Stmt *SubStmt : s->children())
  538. // SubStmt might be null; as in missing decl or conditional of an if-stmt.
  539. if (SubStmt && isAccessedBy(var, SubStmt))
  540. return true;
  541. return false;
  542. }
  543. static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
  544. if (!decl) return false;
  545. if (!isa<VarDecl>(decl)) return false;
  546. const VarDecl *var = cast<VarDecl>(decl);
  547. return isAccessedBy(*var, e);
  548. }
  549. static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
  550. const LValue &destLV, const Expr *init) {
  551. bool needsCast = false;
  552. while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
  553. switch (castExpr->getCastKind()) {
  554. // Look through casts that don't require representation changes.
  555. case CK_NoOp:
  556. case CK_BitCast:
  557. case CK_BlockPointerToObjCPointerCast:
  558. needsCast = true;
  559. break;
  560. // If we find an l-value to r-value cast from a __weak variable,
  561. // emit this operation as a copy or move.
  562. case CK_LValueToRValue: {
  563. const Expr *srcExpr = castExpr->getSubExpr();
  564. if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
  565. return false;
  566. // Emit the source l-value.
  567. LValue srcLV = CGF.EmitLValue(srcExpr);
  568. // Handle a formal type change to avoid asserting.
  569. auto srcAddr = srcLV.getAddress();
  570. if (needsCast) {
  571. srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
  572. destLV.getAddress().getElementType());
  573. }
  574. // If it was an l-value, use objc_copyWeak.
  575. if (srcExpr->getValueKind() == VK_LValue) {
  576. CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
  577. } else {
  578. assert(srcExpr->getValueKind() == VK_XValue);
  579. CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
  580. }
  581. return true;
  582. }
  583. // Stop at anything else.
  584. default:
  585. return false;
  586. }
  587. init = castExpr->getSubExpr();
  588. }
  589. return false;
  590. }
  591. static void drillIntoBlockVariable(CodeGenFunction &CGF,
  592. LValue &lvalue,
  593. const VarDecl *var) {
  594. lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
  595. }
  596. void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
  597. SourceLocation Loc) {
  598. if (!SanOpts.has(SanitizerKind::NullabilityAssign))
  599. return;
  600. auto Nullability = LHS.getType()->getNullability(getContext());
  601. if (!Nullability || *Nullability != NullabilityKind::NonNull)
  602. return;
  603. // Check if the right hand side of the assignment is nonnull, if the left
  604. // hand side must be nonnull.
  605. SanitizerScope SanScope(this);
  606. llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
  607. llvm::Constant *StaticData[] = {
  608. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
  609. llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
  610. llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
  611. EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
  612. SanitizerHandler::TypeMismatch, StaticData, RHS);
  613. }
  614. void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
  615. LValue lvalue, bool capturedByInit) {
  616. Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
  617. if (!lifetime) {
  618. llvm::Value *value = EmitScalarExpr(init);
  619. if (capturedByInit)
  620. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  621. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  622. EmitStoreThroughLValue(RValue::get(value), lvalue, true);
  623. return;
  624. }
  625. if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
  626. init = DIE->getExpr();
  627. // If we're emitting a value with lifetime, we have to do the
  628. // initialization *before* we leave the cleanup scopes.
  629. if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
  630. enterFullExpression(ewc);
  631. init = ewc->getSubExpr();
  632. }
  633. CodeGenFunction::RunCleanupsScope Scope(*this);
  634. // We have to maintain the illusion that the variable is
  635. // zero-initialized. If the variable might be accessed in its
  636. // initializer, zero-initialize before running the initializer, then
  637. // actually perform the initialization with an assign.
  638. bool accessedByInit = false;
  639. if (lifetime != Qualifiers::OCL_ExplicitNone)
  640. accessedByInit = (capturedByInit || isAccessedBy(D, init));
  641. if (accessedByInit) {
  642. LValue tempLV = lvalue;
  643. // Drill down to the __block object if necessary.
  644. if (capturedByInit) {
  645. // We can use a simple GEP for this because it can't have been
  646. // moved yet.
  647. tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
  648. cast<VarDecl>(D),
  649. /*follow*/ false));
  650. }
  651. auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
  652. llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
  653. // If __weak, we want to use a barrier under certain conditions.
  654. if (lifetime == Qualifiers::OCL_Weak)
  655. EmitARCInitWeak(tempLV.getAddress(), zero);
  656. // Otherwise just do a simple store.
  657. else
  658. EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
  659. }
  660. // Emit the initializer.
  661. llvm::Value *value = nullptr;
  662. switch (lifetime) {
  663. case Qualifiers::OCL_None:
  664. llvm_unreachable("present but none");
  665. case Qualifiers::OCL_ExplicitNone:
  666. value = EmitARCUnsafeUnretainedScalarExpr(init);
  667. break;
  668. case Qualifiers::OCL_Strong: {
  669. value = EmitARCRetainScalarExpr(init);
  670. break;
  671. }
  672. case Qualifiers::OCL_Weak: {
  673. // If it's not accessed by the initializer, try to emit the
  674. // initialization with a copy or move.
  675. if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
  676. return;
  677. }
  678. // No way to optimize a producing initializer into this. It's not
  679. // worth optimizing for, because the value will immediately
  680. // disappear in the common case.
  681. value = EmitScalarExpr(init);
  682. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  683. if (accessedByInit)
  684. EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
  685. else
  686. EmitARCInitWeak(lvalue.getAddress(), value);
  687. return;
  688. }
  689. case Qualifiers::OCL_Autoreleasing:
  690. value = EmitARCRetainAutoreleaseScalarExpr(init);
  691. break;
  692. }
  693. if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  694. EmitNullabilityCheck(lvalue, value, init->getExprLoc());
  695. // If the variable might have been accessed by its initializer, we
  696. // might have to initialize with a barrier. We have to do this for
  697. // both __weak and __strong, but __weak got filtered out above.
  698. if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
  699. llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
  700. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  701. EmitARCRelease(oldValue, ARCImpreciseLifetime);
  702. return;
  703. }
  704. EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
  705. }
  706. /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
  707. /// non-zero parts of the specified initializer with equal or fewer than
  708. /// NumStores scalar stores.
  709. static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
  710. unsigned &NumStores) {
  711. // Zero and Undef never requires any extra stores.
  712. if (isa<llvm::ConstantAggregateZero>(Init) ||
  713. isa<llvm::ConstantPointerNull>(Init) ||
  714. isa<llvm::UndefValue>(Init))
  715. return true;
  716. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  717. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  718. isa<llvm::ConstantExpr>(Init))
  719. return Init->isNullValue() || NumStores--;
  720. // See if we can emit each element.
  721. if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
  722. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  723. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  724. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  725. return false;
  726. }
  727. return true;
  728. }
  729. if (llvm::ConstantDataSequential *CDS =
  730. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  731. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  732. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  733. if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
  734. return false;
  735. }
  736. return true;
  737. }
  738. // Anything else is hard and scary.
  739. return false;
  740. }
  741. /// emitStoresForInitAfterMemset - For inits that
  742. /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
  743. /// stores that would be required.
  744. static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
  745. bool isVolatile, CGBuilderTy &Builder) {
  746. assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
  747. "called emitStoresForInitAfterMemset for zero or undef value.");
  748. if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
  749. isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
  750. isa<llvm::ConstantExpr>(Init)) {
  751. Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
  752. return;
  753. }
  754. if (llvm::ConstantDataSequential *CDS =
  755. dyn_cast<llvm::ConstantDataSequential>(Init)) {
  756. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  757. llvm::Constant *Elt = CDS->getElementAsConstant(i);
  758. // If necessary, get a pointer to the element and emit it.
  759. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  760. emitStoresForInitAfterMemset(
  761. Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
  762. isVolatile, Builder);
  763. }
  764. return;
  765. }
  766. assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
  767. "Unknown value type!");
  768. for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
  769. llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
  770. // If necessary, get a pointer to the element and emit it.
  771. if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
  772. emitStoresForInitAfterMemset(
  773. Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
  774. isVolatile, Builder);
  775. }
  776. }
  777. /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
  778. /// plus some stores to initialize a local variable instead of using a memcpy
  779. /// from a constant global. It is beneficial to use memset if the global is all
  780. /// zeros, or mostly zeros and large.
  781. static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
  782. uint64_t GlobalSize) {
  783. // If a global is all zeros, always use a memset.
  784. if (isa<llvm::ConstantAggregateZero>(Init)) return true;
  785. // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
  786. // do it if it will require 6 or fewer scalar stores.
  787. // TODO: Should budget depends on the size? Avoiding a large global warrants
  788. // plopping in more stores.
  789. unsigned StoreBudget = 6;
  790. uint64_t SizeLimit = 32;
  791. return GlobalSize > SizeLimit &&
  792. canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
  793. }
  794. /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
  795. /// variable declaration with auto, register, or no storage class specifier.
  796. /// These turn into simple stack objects, or GlobalValues depending on target.
  797. void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
  798. AutoVarEmission emission = EmitAutoVarAlloca(D);
  799. EmitAutoVarInit(emission);
  800. EmitAutoVarCleanups(emission);
  801. }
  802. /// Emit a lifetime.begin marker if some criteria are satisfied.
  803. /// \return a pointer to the temporary size Value if a marker was emitted, null
  804. /// otherwise
  805. llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
  806. llvm::Value *Addr) {
  807. if (!ShouldEmitLifetimeMarkers)
  808. return nullptr;
  809. llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
  810. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  811. llvm::CallInst *C =
  812. Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
  813. C->setDoesNotThrow();
  814. return SizeV;
  815. }
  816. void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
  817. Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
  818. llvm::CallInst *C =
  819. Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
  820. C->setDoesNotThrow();
  821. }
  822. void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
  823. CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
  824. // For each dimension stores its QualType and corresponding
  825. // size-expression Value.
  826. SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
  827. // Break down the array into individual dimensions.
  828. QualType Type1D = D.getType();
  829. while (getContext().getAsVariableArrayType(Type1D)) {
  830. auto VlaSize = getVLAElements1D(Type1D);
  831. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  832. Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
  833. else {
  834. auto SizeExprAddr =
  835. CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), "vla_expr");
  836. Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
  837. Dimensions.emplace_back(SizeExprAddr.getPointer(),
  838. Type1D.getUnqualifiedType());
  839. }
  840. Type1D = VlaSize.Type;
  841. }
  842. if (!EmitDebugInfo)
  843. return;
  844. // Register each dimension's size-expression with a DILocalVariable,
  845. // so that it can be used by CGDebugInfo when instantiating a DISubrange
  846. // to describe this array.
  847. for (auto &VlaSize : Dimensions) {
  848. llvm::Metadata *MD;
  849. if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
  850. MD = llvm::ConstantAsMetadata::get(C);
  851. else {
  852. // Create an artificial VarDecl to generate debug info for.
  853. IdentifierInfo &NameIdent = getContext().Idents.getOwn(
  854. cast<llvm::AllocaInst>(VlaSize.NumElts)->getName());
  855. auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
  856. auto QT = getContext().getIntTypeForBitwidth(
  857. VlaExprTy->getScalarSizeInBits(), false);
  858. auto *ArtificialDecl = VarDecl::Create(
  859. getContext(), const_cast<DeclContext *>(D.getDeclContext()),
  860. D.getLocation(), D.getLocation(), &NameIdent, QT,
  861. getContext().CreateTypeSourceInfo(QT), SC_Auto);
  862. MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
  863. Builder);
  864. }
  865. assert(MD && "No Size expression debug node created");
  866. DI->registerVLASizeExpression(VlaSize.Type, MD);
  867. }
  868. }
  869. /// EmitAutoVarAlloca - Emit the alloca and debug information for a
  870. /// local variable. Does not emit initialization or destruction.
  871. CodeGenFunction::AutoVarEmission
  872. CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
  873. QualType Ty = D.getType();
  874. assert(
  875. Ty.getAddressSpace() == LangAS::Default ||
  876. (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
  877. AutoVarEmission emission(D);
  878. bool isByRef = D.hasAttr<BlocksAttr>();
  879. emission.IsByRef = isByRef;
  880. CharUnits alignment = getContext().getDeclAlign(&D);
  881. // If the type is variably-modified, emit all the VLA sizes for it.
  882. if (Ty->isVariablyModifiedType())
  883. EmitVariablyModifiedType(Ty);
  884. auto *DI = getDebugInfo();
  885. bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
  886. codegenoptions::LimitedDebugInfo;
  887. Address address = Address::invalid();
  888. if (Ty->isConstantSizeType()) {
  889. bool NRVO = getLangOpts().ElideConstructors &&
  890. D.isNRVOVariable();
  891. // If this value is an array or struct with a statically determinable
  892. // constant initializer, there are optimizations we can do.
  893. //
  894. // TODO: We should constant-evaluate the initializer of any variable,
  895. // as long as it is initialized by a constant expression. Currently,
  896. // isConstantInitializer produces wrong answers for structs with
  897. // reference or bitfield members, and a few other cases, and checking
  898. // for POD-ness protects us from some of these.
  899. if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
  900. (D.isConstexpr() ||
  901. ((Ty.isPODType(getContext()) ||
  902. getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
  903. D.getInit()->isConstantInitializer(getContext(), false)))) {
  904. // If the variable's a const type, and it's neither an NRVO
  905. // candidate nor a __block variable and has no mutable members,
  906. // emit it as a global instead.
  907. // Exception is if a variable is located in non-constant address space
  908. // in OpenCL.
  909. if ((!getLangOpts().OpenCL ||
  910. Ty.getAddressSpace() == LangAS::opencl_constant) &&
  911. (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
  912. CGM.isTypeConstant(Ty, true))) {
  913. EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
  914. // Signal this condition to later callbacks.
  915. emission.Addr = Address::invalid();
  916. assert(emission.wasEmittedAsGlobal());
  917. return emission;
  918. }
  919. // Otherwise, tell the initialization code that we're in this case.
  920. emission.IsConstantAggregate = true;
  921. }
  922. // A normal fixed sized variable becomes an alloca in the entry block,
  923. // unless it's an NRVO variable.
  924. if (NRVO) {
  925. // The named return value optimization: allocate this variable in the
  926. // return slot, so that we can elide the copy when returning this
  927. // variable (C++0x [class.copy]p34).
  928. address = ReturnValue;
  929. if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
  930. if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
  931. // Create a flag that is used to indicate when the NRVO was applied
  932. // to this variable. Set it to zero to indicate that NRVO was not
  933. // applied.
  934. llvm::Value *Zero = Builder.getFalse();
  935. Address NRVOFlag =
  936. CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
  937. EnsureInsertPoint();
  938. Builder.CreateStore(Zero, NRVOFlag);
  939. // Record the NRVO flag for this variable.
  940. NRVOFlags[&D] = NRVOFlag.getPointer();
  941. emission.NRVOFlag = NRVOFlag.getPointer();
  942. }
  943. }
  944. } else {
  945. CharUnits allocaAlignment;
  946. llvm::Type *allocaTy;
  947. if (isByRef) {
  948. auto &byrefInfo = getBlockByrefInfo(&D);
  949. allocaTy = byrefInfo.Type;
  950. allocaAlignment = byrefInfo.ByrefAlignment;
  951. } else {
  952. allocaTy = ConvertTypeForMem(Ty);
  953. allocaAlignment = alignment;
  954. }
  955. // Create the alloca. Note that we set the name separately from
  956. // building the instruction so that it's there even in no-asserts
  957. // builds.
  958. address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName());
  959. // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
  960. // the catch parameter starts in the catchpad instruction, and we can't
  961. // insert code in those basic blocks.
  962. bool IsMSCatchParam =
  963. D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
  964. // Emit a lifetime intrinsic if meaningful. There's no point in doing this
  965. // if we don't have a valid insertion point (?).
  966. if (HaveInsertPoint() && !IsMSCatchParam) {
  967. // If there's a jump into the lifetime of this variable, its lifetime
  968. // gets broken up into several regions in IR, which requires more work
  969. // to handle correctly. For now, just omit the intrinsics; this is a
  970. // rare case, and it's better to just be conservatively correct.
  971. // PR28267.
  972. //
  973. // We have to do this in all language modes if there's a jump past the
  974. // declaration. We also have to do it in C if there's a jump to an
  975. // earlier point in the current block because non-VLA lifetimes begin as
  976. // soon as the containing block is entered, not when its variables
  977. // actually come into scope; suppressing the lifetime annotations
  978. // completely in this case is unnecessarily pessimistic, but again, this
  979. // is rare.
  980. if (!Bypasses.IsBypassed(&D) &&
  981. !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
  982. uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
  983. emission.SizeForLifetimeMarkers =
  984. EmitLifetimeStart(size, address.getPointer());
  985. }
  986. } else {
  987. assert(!emission.useLifetimeMarkers());
  988. }
  989. }
  990. } else {
  991. EnsureInsertPoint();
  992. if (!DidCallStackSave) {
  993. // Save the stack.
  994. Address Stack =
  995. CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
  996. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  997. llvm::Value *V = Builder.CreateCall(F);
  998. Builder.CreateStore(V, Stack);
  999. DidCallStackSave = true;
  1000. // Push a cleanup block and restore the stack there.
  1001. // FIXME: in general circumstances, this should be an EH cleanup.
  1002. pushStackRestore(NormalCleanup, Stack);
  1003. }
  1004. auto VlaSize = getVLASize(Ty);
  1005. llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
  1006. // Allocate memory for the array.
  1007. address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts);
  1008. // If we have debug info enabled, properly describe the VLA dimensions for
  1009. // this type by registering the vla size expression for each of the
  1010. // dimensions.
  1011. EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
  1012. }
  1013. setAddrOfLocalVar(&D, address);
  1014. emission.Addr = address;
  1015. // Emit debug info for local var declaration.
  1016. if (EmitDebugInfo && HaveInsertPoint()) {
  1017. DI->setLocation(D.getLocation());
  1018. (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
  1019. }
  1020. if (D.hasAttr<AnnotateAttr>())
  1021. EmitVarAnnotations(&D, address.getPointer());
  1022. // Make sure we call @llvm.lifetime.end.
  1023. if (emission.useLifetimeMarkers())
  1024. EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
  1025. emission.getAllocatedAddress(),
  1026. emission.getSizeForLifetimeMarkers());
  1027. return emission;
  1028. }
  1029. /// Determines whether the given __block variable is potentially
  1030. /// captured by the given expression.
  1031. static bool isCapturedBy(const VarDecl &var, const Expr *e) {
  1032. // Skip the most common kinds of expressions that make
  1033. // hierarchy-walking expensive.
  1034. e = e->IgnoreParenCasts();
  1035. if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
  1036. const BlockDecl *block = be->getBlockDecl();
  1037. for (const auto &I : block->captures()) {
  1038. if (I.getVariable() == &var)
  1039. return true;
  1040. }
  1041. // No need to walk into the subexpressions.
  1042. return false;
  1043. }
  1044. if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
  1045. const CompoundStmt *CS = SE->getSubStmt();
  1046. for (const auto *BI : CS->body())
  1047. if (const auto *E = dyn_cast<Expr>(BI)) {
  1048. if (isCapturedBy(var, E))
  1049. return true;
  1050. }
  1051. else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
  1052. // special case declarations
  1053. for (const auto *I : DS->decls()) {
  1054. if (const auto *VD = dyn_cast<VarDecl>((I))) {
  1055. const Expr *Init = VD->getInit();
  1056. if (Init && isCapturedBy(var, Init))
  1057. return true;
  1058. }
  1059. }
  1060. }
  1061. else
  1062. // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
  1063. // Later, provide code to poke into statements for capture analysis.
  1064. return true;
  1065. return false;
  1066. }
  1067. for (const Stmt *SubStmt : e->children())
  1068. if (isCapturedBy(var, cast<Expr>(SubStmt)))
  1069. return true;
  1070. return false;
  1071. }
  1072. /// \brief Determine whether the given initializer is trivial in the sense
  1073. /// that it requires no code to be generated.
  1074. bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
  1075. if (!Init)
  1076. return true;
  1077. if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
  1078. if (CXXConstructorDecl *Constructor = Construct->getConstructor())
  1079. if (Constructor->isTrivial() &&
  1080. Constructor->isDefaultConstructor() &&
  1081. !Construct->requiresZeroInitialization())
  1082. return true;
  1083. return false;
  1084. }
  1085. void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
  1086. assert(emission.Variable && "emission was not valid!");
  1087. // If this was emitted as a global constant, we're done.
  1088. if (emission.wasEmittedAsGlobal()) return;
  1089. const VarDecl &D = *emission.Variable;
  1090. auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
  1091. QualType type = D.getType();
  1092. // If this local has an initializer, emit it now.
  1093. const Expr *Init = D.getInit();
  1094. // If we are at an unreachable point, we don't need to emit the initializer
  1095. // unless it contains a label.
  1096. if (!HaveInsertPoint()) {
  1097. if (!Init || !ContainsLabel(Init)) return;
  1098. EnsureInsertPoint();
  1099. }
  1100. // Initialize the structure of a __block variable.
  1101. if (emission.IsByRef)
  1102. emitByrefStructureInit(emission);
  1103. if (isTrivialInitializer(Init))
  1104. return;
  1105. // Check whether this is a byref variable that's potentially
  1106. // captured and moved by its own initializer. If so, we'll need to
  1107. // emit the initializer first, then copy into the variable.
  1108. bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
  1109. Address Loc =
  1110. capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
  1111. llvm::Constant *constant = nullptr;
  1112. if (emission.IsConstantAggregate || D.isConstexpr()) {
  1113. assert(!capturedByInit && "constant init contains a capturing block?");
  1114. constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
  1115. }
  1116. if (!constant) {
  1117. LValue lv = MakeAddrLValue(Loc, type);
  1118. lv.setNonGC(true);
  1119. return EmitExprAsInit(Init, &D, lv, capturedByInit);
  1120. }
  1121. if (!emission.IsConstantAggregate) {
  1122. // For simple scalar/complex initialization, store the value directly.
  1123. LValue lv = MakeAddrLValue(Loc, type);
  1124. lv.setNonGC(true);
  1125. return EmitStoreThroughLValue(RValue::get(constant), lv, true);
  1126. }
  1127. // If this is a simple aggregate initialization, we can optimize it
  1128. // in various ways.
  1129. bool isVolatile = type.isVolatileQualified();
  1130. llvm::Value *SizeVal =
  1131. llvm::ConstantInt::get(IntPtrTy,
  1132. getContext().getTypeSizeInChars(type).getQuantity());
  1133. llvm::Type *BP = AllocaInt8PtrTy;
  1134. if (Loc.getType() != BP)
  1135. Loc = Builder.CreateBitCast(Loc, BP);
  1136. // If the initializer is all or mostly zeros, codegen with memset then do
  1137. // a few stores afterward.
  1138. if (shouldUseMemSetPlusStoresToInitialize(constant,
  1139. CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
  1140. Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
  1141. isVolatile);
  1142. // Zero and undef don't require a stores.
  1143. if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
  1144. Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
  1145. emitStoresForInitAfterMemset(constant, Loc.getPointer(),
  1146. isVolatile, Builder);
  1147. }
  1148. } else {
  1149. // Otherwise, create a temporary global with the initializer then
  1150. // memcpy from the global to the alloca.
  1151. std::string Name = getStaticDeclName(CGM, D);
  1152. unsigned AS = 0;
  1153. if (getLangOpts().OpenCL) {
  1154. AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  1155. BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
  1156. }
  1157. llvm::GlobalVariable *GV =
  1158. new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
  1159. llvm::GlobalValue::PrivateLinkage,
  1160. constant, Name, nullptr,
  1161. llvm::GlobalValue::NotThreadLocal, AS);
  1162. GV->setAlignment(Loc.getAlignment().getQuantity());
  1163. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1164. Address SrcPtr = Address(GV, Loc.getAlignment());
  1165. if (SrcPtr.getType() != BP)
  1166. SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
  1167. Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
  1168. }
  1169. }
  1170. /// Emit an expression as an initializer for a variable at the given
  1171. /// location. The expression is not necessarily the normal
  1172. /// initializer for the variable, and the address is not necessarily
  1173. /// its normal location.
  1174. ///
  1175. /// \param init the initializing expression
  1176. /// \param var the variable to act as if we're initializing
  1177. /// \param loc the address to initialize; its type is a pointer
  1178. /// to the LLVM mapping of the variable's type
  1179. /// \param alignment the alignment of the address
  1180. /// \param capturedByInit true if the variable is a __block variable
  1181. /// whose address is potentially changed by the initializer
  1182. void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1183. LValue lvalue, bool capturedByInit) {
  1184. QualType type = D->getType();
  1185. if (type->isReferenceType()) {
  1186. RValue rvalue = EmitReferenceBindingToExpr(init);
  1187. if (capturedByInit)
  1188. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1189. EmitStoreThroughLValue(rvalue, lvalue, true);
  1190. return;
  1191. }
  1192. switch (getEvaluationKind(type)) {
  1193. case TEK_Scalar:
  1194. EmitScalarInit(init, D, lvalue, capturedByInit);
  1195. return;
  1196. case TEK_Complex: {
  1197. ComplexPairTy complex = EmitComplexExpr(init);
  1198. if (capturedByInit)
  1199. drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
  1200. EmitStoreOfComplex(complex, lvalue, /*init*/ true);
  1201. return;
  1202. }
  1203. case TEK_Aggregate:
  1204. if (type->isAtomicType()) {
  1205. EmitAtomicInit(const_cast<Expr*>(init), lvalue);
  1206. } else {
  1207. // TODO: how can we delay here if D is captured by its initializer?
  1208. EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
  1209. AggValueSlot::IsDestructed,
  1210. AggValueSlot::DoesNotNeedGCBarriers,
  1211. AggValueSlot::IsNotAliased));
  1212. }
  1213. return;
  1214. }
  1215. llvm_unreachable("bad evaluation kind");
  1216. }
  1217. /// Enter a destroy cleanup for the given local variable.
  1218. void CodeGenFunction::emitAutoVarTypeCleanup(
  1219. const CodeGenFunction::AutoVarEmission &emission,
  1220. QualType::DestructionKind dtorKind) {
  1221. assert(dtorKind != QualType::DK_none);
  1222. // Note that for __block variables, we want to destroy the
  1223. // original stack object, not the possibly forwarded object.
  1224. Address addr = emission.getObjectAddress(*this);
  1225. const VarDecl *var = emission.Variable;
  1226. QualType type = var->getType();
  1227. CleanupKind cleanupKind = NormalAndEHCleanup;
  1228. CodeGenFunction::Destroyer *destroyer = nullptr;
  1229. switch (dtorKind) {
  1230. case QualType::DK_none:
  1231. llvm_unreachable("no cleanup for trivially-destructible variable");
  1232. case QualType::DK_cxx_destructor:
  1233. // If there's an NRVO flag on the emission, we need a different
  1234. // cleanup.
  1235. if (emission.NRVOFlag) {
  1236. assert(!type->isArrayType());
  1237. CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
  1238. EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
  1239. dtor, emission.NRVOFlag);
  1240. return;
  1241. }
  1242. break;
  1243. case QualType::DK_objc_strong_lifetime:
  1244. // Suppress cleanups for pseudo-strong variables.
  1245. if (var->isARCPseudoStrong()) return;
  1246. // Otherwise, consider whether to use an EH cleanup or not.
  1247. cleanupKind = getARCCleanupKind();
  1248. // Use the imprecise destroyer by default.
  1249. if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
  1250. destroyer = CodeGenFunction::destroyARCStrongImprecise;
  1251. break;
  1252. case QualType::DK_objc_weak_lifetime:
  1253. break;
  1254. }
  1255. // If we haven't chosen a more specific destroyer, use the default.
  1256. if (!destroyer) destroyer = getDestroyer(dtorKind);
  1257. // Use an EH cleanup in array destructors iff the destructor itself
  1258. // is being pushed as an EH cleanup.
  1259. bool useEHCleanup = (cleanupKind & EHCleanup);
  1260. EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
  1261. useEHCleanup);
  1262. }
  1263. void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
  1264. assert(emission.Variable && "emission was not valid!");
  1265. // If this was emitted as a global constant, we're done.
  1266. if (emission.wasEmittedAsGlobal()) return;
  1267. // If we don't have an insertion point, we're done. Sema prevents
  1268. // us from jumping into any of these scopes anyway.
  1269. if (!HaveInsertPoint()) return;
  1270. const VarDecl &D = *emission.Variable;
  1271. // Check the type for a cleanup.
  1272. if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
  1273. emitAutoVarTypeCleanup(emission, dtorKind);
  1274. // In GC mode, honor objc_precise_lifetime.
  1275. if (getLangOpts().getGC() != LangOptions::NonGC &&
  1276. D.hasAttr<ObjCPreciseLifetimeAttr>()) {
  1277. EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
  1278. }
  1279. // Handle the cleanup attribute.
  1280. if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
  1281. const FunctionDecl *FD = CA->getFunctionDecl();
  1282. llvm::Constant *F = CGM.GetAddrOfFunction(FD);
  1283. assert(F && "Could not find function!");
  1284. const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
  1285. EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
  1286. }
  1287. // If this is a block variable, call _Block_object_destroy
  1288. // (on the unforwarded address).
  1289. if (emission.IsByRef)
  1290. enterByrefCleanup(emission);
  1291. }
  1292. CodeGenFunction::Destroyer *
  1293. CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
  1294. switch (kind) {
  1295. case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
  1296. case QualType::DK_cxx_destructor:
  1297. return destroyCXXObject;
  1298. case QualType::DK_objc_strong_lifetime:
  1299. return destroyARCStrongPrecise;
  1300. case QualType::DK_objc_weak_lifetime:
  1301. return destroyARCWeak;
  1302. }
  1303. llvm_unreachable("Unknown DestructionKind");
  1304. }
  1305. /// pushEHDestroy - Push the standard destructor for the given type as
  1306. /// an EH-only cleanup.
  1307. void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
  1308. Address addr, QualType type) {
  1309. assert(dtorKind && "cannot push destructor for trivial type");
  1310. assert(needsEHCleanup(dtorKind));
  1311. pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
  1312. }
  1313. /// pushDestroy - Push the standard destructor for the given type as
  1314. /// at least a normal cleanup.
  1315. void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
  1316. Address addr, QualType type) {
  1317. assert(dtorKind && "cannot push destructor for trivial type");
  1318. CleanupKind cleanupKind = getCleanupKind(dtorKind);
  1319. pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
  1320. cleanupKind & EHCleanup);
  1321. }
  1322. void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
  1323. QualType type, Destroyer *destroyer,
  1324. bool useEHCleanupForArray) {
  1325. pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
  1326. destroyer, useEHCleanupForArray);
  1327. }
  1328. void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
  1329. EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
  1330. }
  1331. void CodeGenFunction::pushLifetimeExtendedDestroy(
  1332. CleanupKind cleanupKind, Address addr, QualType type,
  1333. Destroyer *destroyer, bool useEHCleanupForArray) {
  1334. assert(!isInConditionalBranch() &&
  1335. "performing lifetime extension from within conditional");
  1336. // Push an EH-only cleanup for the object now.
  1337. // FIXME: When popping normal cleanups, we need to keep this EH cleanup
  1338. // around in case a temporary's destructor throws an exception.
  1339. if (cleanupKind & EHCleanup)
  1340. EHStack.pushCleanup<DestroyObject>(
  1341. static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
  1342. destroyer, useEHCleanupForArray);
  1343. // Remember that we need to push a full cleanup for the object at the
  1344. // end of the full-expression.
  1345. pushCleanupAfterFullExpr<DestroyObject>(
  1346. cleanupKind, addr, type, destroyer, useEHCleanupForArray);
  1347. }
  1348. /// emitDestroy - Immediately perform the destruction of the given
  1349. /// object.
  1350. ///
  1351. /// \param addr - the address of the object; a type*
  1352. /// \param type - the type of the object; if an array type, all
  1353. /// objects are destroyed in reverse order
  1354. /// \param destroyer - the function to call to destroy individual
  1355. /// elements
  1356. /// \param useEHCleanupForArray - whether an EH cleanup should be
  1357. /// used when destroying array elements, in case one of the
  1358. /// destructions throws an exception
  1359. void CodeGenFunction::emitDestroy(Address addr, QualType type,
  1360. Destroyer *destroyer,
  1361. bool useEHCleanupForArray) {
  1362. const ArrayType *arrayType = getContext().getAsArrayType(type);
  1363. if (!arrayType)
  1364. return destroyer(*this, addr, type);
  1365. llvm::Value *length = emitArrayLength(arrayType, type, addr);
  1366. CharUnits elementAlign =
  1367. addr.getAlignment()
  1368. .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
  1369. // Normally we have to check whether the array is zero-length.
  1370. bool checkZeroLength = true;
  1371. // But if the array length is constant, we can suppress that.
  1372. if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
  1373. // ...and if it's constant zero, we can just skip the entire thing.
  1374. if (constLength->isZero()) return;
  1375. checkZeroLength = false;
  1376. }
  1377. llvm::Value *begin = addr.getPointer();
  1378. llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
  1379. emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1380. checkZeroLength, useEHCleanupForArray);
  1381. }
  1382. /// emitArrayDestroy - Destroys all the elements of the given array,
  1383. /// beginning from last to first. The array cannot be zero-length.
  1384. ///
  1385. /// \param begin - a type* denoting the first element of the array
  1386. /// \param end - a type* denoting one past the end of the array
  1387. /// \param elementType - the element type of the array
  1388. /// \param destroyer - the function to call to destroy elements
  1389. /// \param useEHCleanup - whether to push an EH cleanup to destroy
  1390. /// the remaining elements in case the destruction of a single
  1391. /// element throws
  1392. void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
  1393. llvm::Value *end,
  1394. QualType elementType,
  1395. CharUnits elementAlign,
  1396. Destroyer *destroyer,
  1397. bool checkZeroLength,
  1398. bool useEHCleanup) {
  1399. assert(!elementType->isArrayType());
  1400. // The basic structure here is a do-while loop, because we don't
  1401. // need to check for the zero-element case.
  1402. llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
  1403. llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
  1404. if (checkZeroLength) {
  1405. llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
  1406. "arraydestroy.isempty");
  1407. Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
  1408. }
  1409. // Enter the loop body, making that address the current address.
  1410. llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
  1411. EmitBlock(bodyBB);
  1412. llvm::PHINode *elementPast =
  1413. Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
  1414. elementPast->addIncoming(end, entryBB);
  1415. // Shift the address back by one element.
  1416. llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
  1417. llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
  1418. "arraydestroy.element");
  1419. if (useEHCleanup)
  1420. pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
  1421. destroyer);
  1422. // Perform the actual destruction there.
  1423. destroyer(*this, Address(element, elementAlign), elementType);
  1424. if (useEHCleanup)
  1425. PopCleanupBlock();
  1426. // Check whether we've reached the end.
  1427. llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
  1428. Builder.CreateCondBr(done, doneBB, bodyBB);
  1429. elementPast->addIncoming(element, Builder.GetInsertBlock());
  1430. // Done.
  1431. EmitBlock(doneBB);
  1432. }
  1433. /// Perform partial array destruction as if in an EH cleanup. Unlike
  1434. /// emitArrayDestroy, the element type here may still be an array type.
  1435. static void emitPartialArrayDestroy(CodeGenFunction &CGF,
  1436. llvm::Value *begin, llvm::Value *end,
  1437. QualType type, CharUnits elementAlign,
  1438. CodeGenFunction::Destroyer *destroyer) {
  1439. // If the element type is itself an array, drill down.
  1440. unsigned arrayDepth = 0;
  1441. while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
  1442. // VLAs don't require a GEP index to walk into.
  1443. if (!isa<VariableArrayType>(arrayType))
  1444. arrayDepth++;
  1445. type = arrayType->getElementType();
  1446. }
  1447. if (arrayDepth) {
  1448. llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
  1449. SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
  1450. begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
  1451. end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
  1452. }
  1453. // Destroy the array. We don't ever need an EH cleanup because we
  1454. // assume that we're in an EH cleanup ourselves, so a throwing
  1455. // destructor causes an immediate terminate.
  1456. CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
  1457. /*checkZeroLength*/ true, /*useEHCleanup*/ false);
  1458. }
  1459. namespace {
  1460. /// RegularPartialArrayDestroy - a cleanup which performs a partial
  1461. /// array destroy where the end pointer is regularly determined and
  1462. /// does not need to be loaded from a local.
  1463. class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1464. llvm::Value *ArrayBegin;
  1465. llvm::Value *ArrayEnd;
  1466. QualType ElementType;
  1467. CodeGenFunction::Destroyer *Destroyer;
  1468. CharUnits ElementAlign;
  1469. public:
  1470. RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
  1471. QualType elementType, CharUnits elementAlign,
  1472. CodeGenFunction::Destroyer *destroyer)
  1473. : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
  1474. ElementType(elementType), Destroyer(destroyer),
  1475. ElementAlign(elementAlign) {}
  1476. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1477. emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
  1478. ElementType, ElementAlign, Destroyer);
  1479. }
  1480. };
  1481. /// IrregularPartialArrayDestroy - a cleanup which performs a
  1482. /// partial array destroy where the end pointer is irregularly
  1483. /// determined and must be loaded from a local.
  1484. class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
  1485. llvm::Value *ArrayBegin;
  1486. Address ArrayEndPointer;
  1487. QualType ElementType;
  1488. CodeGenFunction::Destroyer *Destroyer;
  1489. CharUnits ElementAlign;
  1490. public:
  1491. IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
  1492. Address arrayEndPointer,
  1493. QualType elementType,
  1494. CharUnits elementAlign,
  1495. CodeGenFunction::Destroyer *destroyer)
  1496. : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
  1497. ElementType(elementType), Destroyer(destroyer),
  1498. ElementAlign(elementAlign) {}
  1499. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1500. llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
  1501. emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
  1502. ElementType, ElementAlign, Destroyer);
  1503. }
  1504. };
  1505. } // end anonymous namespace
  1506. /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
  1507. /// already-constructed elements of the given array. The cleanup
  1508. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1509. ///
  1510. /// \param elementType - the immediate element type of the array;
  1511. /// possibly still an array type
  1512. void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1513. Address arrayEndPointer,
  1514. QualType elementType,
  1515. CharUnits elementAlign,
  1516. Destroyer *destroyer) {
  1517. pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
  1518. arrayBegin, arrayEndPointer,
  1519. elementType, elementAlign,
  1520. destroyer);
  1521. }
  1522. /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
  1523. /// already-constructed elements of the given array. The cleanup
  1524. /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
  1525. ///
  1526. /// \param elementType - the immediate element type of the array;
  1527. /// possibly still an array type
  1528. void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1529. llvm::Value *arrayEnd,
  1530. QualType elementType,
  1531. CharUnits elementAlign,
  1532. Destroyer *destroyer) {
  1533. pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
  1534. arrayBegin, arrayEnd,
  1535. elementType, elementAlign,
  1536. destroyer);
  1537. }
  1538. /// Lazily declare the @llvm.lifetime.start intrinsic.
  1539. llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
  1540. if (LifetimeStartFn)
  1541. return LifetimeStartFn;
  1542. LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1543. llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
  1544. return LifetimeStartFn;
  1545. }
  1546. /// Lazily declare the @llvm.lifetime.end intrinsic.
  1547. llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
  1548. if (LifetimeEndFn)
  1549. return LifetimeEndFn;
  1550. LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
  1551. llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
  1552. return LifetimeEndFn;
  1553. }
  1554. namespace {
  1555. /// A cleanup to perform a release of an object at the end of a
  1556. /// function. This is used to balance out the incoming +1 of a
  1557. /// ns_consumed argument when we can't reasonably do that just by
  1558. /// not doing the initial retain for a __block argument.
  1559. struct ConsumeARCParameter final : EHScopeStack::Cleanup {
  1560. ConsumeARCParameter(llvm::Value *param,
  1561. ARCPreciseLifetime_t precise)
  1562. : Param(param), Precise(precise) {}
  1563. llvm::Value *Param;
  1564. ARCPreciseLifetime_t Precise;
  1565. void Emit(CodeGenFunction &CGF, Flags flags) override {
  1566. CGF.EmitARCRelease(Param, Precise);
  1567. }
  1568. };
  1569. } // end anonymous namespace
  1570. /// Emit an alloca (or GlobalValue depending on target)
  1571. /// for the specified parameter and set up LocalDeclMap.
  1572. void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
  1573. unsigned ArgNo) {
  1574. // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
  1575. assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
  1576. "Invalid argument to EmitParmDecl");
  1577. Arg.getAnyValue()->setName(D.getName());
  1578. QualType Ty = D.getType();
  1579. // Use better IR generation for certain implicit parameters.
  1580. if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
  1581. // The only implicit argument a block has is its literal.
  1582. // We assume this is always passed directly.
  1583. if (BlockInfo) {
  1584. setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
  1585. return;
  1586. }
  1587. }
  1588. Address DeclPtr = Address::invalid();
  1589. bool DoStore = false;
  1590. bool IsScalar = hasScalarEvaluationKind(Ty);
  1591. // If we already have a pointer to the argument, reuse the input pointer.
  1592. if (Arg.isIndirect()) {
  1593. DeclPtr = Arg.getIndirectAddress();
  1594. // If we have a prettier pointer type at this point, bitcast to that.
  1595. unsigned AS = DeclPtr.getType()->getAddressSpace();
  1596. llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
  1597. if (DeclPtr.getType() != IRTy)
  1598. DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
  1599. // Push a destructor cleanup for this parameter if the ABI requires it.
  1600. // Don't push a cleanup in a thunk for a method that will also emit a
  1601. // cleanup.
  1602. if (!IsScalar && !CurFuncIsThunk &&
  1603. getContext().isParamDestroyedInCallee(Ty)) {
  1604. const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  1605. if (RD && RD->hasNonTrivialDestructor())
  1606. pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
  1607. }
  1608. } else {
  1609. // Otherwise, create a temporary to hold the value.
  1610. DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
  1611. D.getName() + ".addr");
  1612. DoStore = true;
  1613. }
  1614. llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
  1615. LValue lv = MakeAddrLValue(DeclPtr, Ty);
  1616. if (IsScalar) {
  1617. Qualifiers qs = Ty.getQualifiers();
  1618. if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
  1619. // We honor __attribute__((ns_consumed)) for types with lifetime.
  1620. // For __strong, it's handled by just skipping the initial retain;
  1621. // otherwise we have to balance out the initial +1 with an extra
  1622. // cleanup to do the release at the end of the function.
  1623. bool isConsumed = D.hasAttr<NSConsumedAttr>();
  1624. // 'self' is always formally __strong, but if this is not an
  1625. // init method then we don't want to retain it.
  1626. if (D.isARCPseudoStrong()) {
  1627. const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
  1628. assert(&D == method->getSelfDecl());
  1629. assert(lt == Qualifiers::OCL_Strong);
  1630. assert(qs.hasConst());
  1631. assert(method->getMethodFamily() != OMF_init);
  1632. (void) method;
  1633. lt = Qualifiers::OCL_ExplicitNone;
  1634. }
  1635. // Load objects passed indirectly.
  1636. if (Arg.isIndirect() && !ArgVal)
  1637. ArgVal = Builder.CreateLoad(DeclPtr);
  1638. if (lt == Qualifiers::OCL_Strong) {
  1639. if (!isConsumed) {
  1640. if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
  1641. // use objc_storeStrong(&dest, value) for retaining the
  1642. // object. But first, store a null into 'dest' because
  1643. // objc_storeStrong attempts to release its old value.
  1644. llvm::Value *Null = CGM.EmitNullConstant(D.getType());
  1645. EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
  1646. EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
  1647. DoStore = false;
  1648. }
  1649. else
  1650. // Don't use objc_retainBlock for block pointers, because we
  1651. // don't want to Block_copy something just because we got it
  1652. // as a parameter.
  1653. ArgVal = EmitARCRetainNonBlock(ArgVal);
  1654. }
  1655. } else {
  1656. // Push the cleanup for a consumed parameter.
  1657. if (isConsumed) {
  1658. ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
  1659. ? ARCPreciseLifetime : ARCImpreciseLifetime);
  1660. EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
  1661. precise);
  1662. }
  1663. if (lt == Qualifiers::OCL_Weak) {
  1664. EmitARCInitWeak(DeclPtr, ArgVal);
  1665. DoStore = false; // The weak init is a store, no need to do two.
  1666. }
  1667. }
  1668. // Enter the cleanup scope.
  1669. EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
  1670. }
  1671. }
  1672. // Store the initial value into the alloca.
  1673. if (DoStore)
  1674. EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
  1675. setAddrOfLocalVar(&D, DeclPtr);
  1676. // Emit debug info for param declaration.
  1677. if (CGDebugInfo *DI = getDebugInfo()) {
  1678. if (CGM.getCodeGenOpts().getDebugInfo() >=
  1679. codegenoptions::LimitedDebugInfo) {
  1680. DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
  1681. }
  1682. }
  1683. if (D.hasAttr<AnnotateAttr>())
  1684. EmitVarAnnotations(&D, DeclPtr.getPointer());
  1685. // We can only check return value nullability if all arguments to the
  1686. // function satisfy their nullability preconditions. This makes it necessary
  1687. // to emit null checks for args in the function body itself.
  1688. if (requiresReturnValueNullabilityCheck()) {
  1689. auto Nullability = Ty->getNullability(getContext());
  1690. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  1691. SanitizerScope SanScope(this);
  1692. RetValNullabilityPrecondition =
  1693. Builder.CreateAnd(RetValNullabilityPrecondition,
  1694. Builder.CreateIsNotNull(Arg.getAnyValue()));
  1695. }
  1696. }
  1697. }
  1698. void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
  1699. CodeGenFunction *CGF) {
  1700. if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
  1701. return;
  1702. getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
  1703. }