CGDecl.cpp 69 KB

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