CodeGenModule.cpp 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  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 coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGDebugInfo.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenTBAA.h"
  17. #include "CGCall.h"
  18. #include "CGCUDARuntime.h"
  19. #include "CGCXXABI.h"
  20. #include "CGObjCRuntime.h"
  21. #include "CGOpenCLRuntime.h"
  22. #include "TargetInfo.h"
  23. #include "clang/Frontend/CodeGenOptions.h"
  24. #include "clang/AST/ASTContext.h"
  25. #include "clang/AST/CharUnits.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclCXX.h"
  28. #include "clang/AST/DeclTemplate.h"
  29. #include "clang/AST/Mangle.h"
  30. #include "clang/AST/RecordLayout.h"
  31. #include "clang/AST/RecursiveASTVisitor.h"
  32. #include "clang/Basic/Builtins.h"
  33. #include "clang/Basic/Diagnostic.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/TargetInfo.h"
  36. #include "clang/Basic/ConvertUTF.h"
  37. #include "llvm/CallingConv.h"
  38. #include "llvm/Module.h"
  39. #include "llvm/Intrinsics.h"
  40. #include "llvm/LLVMContext.h"
  41. #include "llvm/ADT/APSInt.h"
  42. #include "llvm/ADT/Triple.h"
  43. #include "llvm/Target/Mangler.h"
  44. #include "llvm/Target/TargetData.h"
  45. #include "llvm/Support/CallSite.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. using namespace clang;
  48. using namespace CodeGen;
  49. static const char AnnotationSection[] = "llvm.metadata";
  50. static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
  51. switch (CGM.getContext().getTargetInfo().getCXXABI()) {
  52. case CXXABI_ARM: return *CreateARMCXXABI(CGM);
  53. case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
  54. case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
  55. }
  56. llvm_unreachable("invalid C++ ABI kind");
  57. }
  58. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  59. llvm::Module &M, const llvm::TargetData &TD,
  60. DiagnosticsEngine &diags)
  61. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  62. TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
  63. ABI(createCXXABI(*this)),
  64. Types(*this),
  65. TBAA(0),
  66. VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
  67. DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
  68. RRData(0), CFConstantStringClassRef(0),
  69. ConstantStringClassRef(0), NSConstantStringType(0),
  70. VMContext(M.getContext()),
  71. NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
  72. BlockObjectAssign(0), BlockObjectDispose(0),
  73. BlockDescriptorType(0), GenericBlockLiteralType(0) {
  74. // Initialize the type cache.
  75. llvm::LLVMContext &LLVMContext = M.getContext();
  76. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  77. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  78. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  79. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  80. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  81. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  82. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  83. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  84. PointerAlignInBytes =
  85. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  86. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  87. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  88. Int8PtrTy = Int8Ty->getPointerTo(0);
  89. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  90. if (LangOpts.ObjC1)
  91. createObjCRuntime();
  92. if (LangOpts.OpenCL)
  93. createOpenCLRuntime();
  94. if (LangOpts.CUDA)
  95. createCUDARuntime();
  96. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  97. if (LangOpts.ThreadSanitizer ||
  98. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  99. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  100. ABI.getMangleContext());
  101. // If debug info or coverage generation is enabled, create the CGDebugInfo
  102. // object.
  103. if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo ||
  104. CodeGenOpts.EmitGcovArcs ||
  105. CodeGenOpts.EmitGcovNotes)
  106. DebugInfo = new CGDebugInfo(*this);
  107. Block.GlobalUniqueCount = 0;
  108. if (C.getLangOpts().ObjCAutoRefCount)
  109. ARCData = new ARCEntrypoints();
  110. RRData = new RREntrypoints();
  111. }
  112. CodeGenModule::~CodeGenModule() {
  113. delete ObjCRuntime;
  114. delete OpenCLRuntime;
  115. delete CUDARuntime;
  116. delete TheTargetCodeGenInfo;
  117. delete &ABI;
  118. delete TBAA;
  119. delete DebugInfo;
  120. delete ARCData;
  121. delete RRData;
  122. }
  123. void CodeGenModule::createObjCRuntime() {
  124. // This is just isGNUFamily(), but we want to force implementors of
  125. // new ABIs to decide how best to do this.
  126. switch (LangOpts.ObjCRuntime.getKind()) {
  127. case ObjCRuntime::GNUstep:
  128. case ObjCRuntime::GCC:
  129. case ObjCRuntime::ObjFW:
  130. ObjCRuntime = CreateGNUObjCRuntime(*this);
  131. return;
  132. case ObjCRuntime::FragileMacOSX:
  133. case ObjCRuntime::MacOSX:
  134. case ObjCRuntime::iOS:
  135. ObjCRuntime = CreateMacObjCRuntime(*this);
  136. return;
  137. }
  138. llvm_unreachable("bad runtime kind");
  139. }
  140. void CodeGenModule::createOpenCLRuntime() {
  141. OpenCLRuntime = new CGOpenCLRuntime(*this);
  142. }
  143. void CodeGenModule::createCUDARuntime() {
  144. CUDARuntime = CreateNVCUDARuntime(*this);
  145. }
  146. void CodeGenModule::Release() {
  147. EmitDeferred();
  148. EmitCXXGlobalInitFunc();
  149. EmitCXXGlobalDtorFunc();
  150. if (ObjCRuntime)
  151. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  152. AddGlobalCtor(ObjCInitFunction);
  153. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  154. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  155. EmitGlobalAnnotations();
  156. EmitLLVMUsed();
  157. SimplifyPersonality();
  158. if (getCodeGenOpts().EmitDeclMetadata)
  159. EmitDeclMetadata();
  160. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  161. EmitCoverageFile();
  162. if (DebugInfo)
  163. DebugInfo->finalize();
  164. }
  165. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  166. // Make sure that this type is translated.
  167. Types.UpdateCompletedType(TD);
  168. }
  169. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  170. if (!TBAA)
  171. return 0;
  172. return TBAA->getTBAAInfo(QTy);
  173. }
  174. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  175. if (!TBAA)
  176. return 0;
  177. return TBAA->getTBAAInfoForVTablePtr();
  178. }
  179. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  180. llvm::MDNode *TBAAInfo) {
  181. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  182. }
  183. bool CodeGenModule::isTargetDarwin() const {
  184. return getContext().getTargetInfo().getTriple().isOSDarwin();
  185. }
  186. void CodeGenModule::Error(SourceLocation loc, StringRef error) {
  187. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
  188. getDiags().Report(Context.getFullLoc(loc), diagID);
  189. }
  190. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  191. /// specified stmt yet.
  192. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
  193. bool OmitOnError) {
  194. if (OmitOnError && getDiags().hasErrorOccurred())
  195. return;
  196. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  197. "cannot compile this %0 yet");
  198. std::string Msg = Type;
  199. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  200. << Msg << S->getSourceRange();
  201. }
  202. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  203. /// specified decl yet.
  204. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
  205. bool OmitOnError) {
  206. if (OmitOnError && getDiags().hasErrorOccurred())
  207. return;
  208. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  209. "cannot compile this %0 yet");
  210. std::string Msg = Type;
  211. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  212. }
  213. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  214. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  215. }
  216. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  217. const NamedDecl *D) const {
  218. // Internal definitions always have default visibility.
  219. if (GV->hasLocalLinkage()) {
  220. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  221. return;
  222. }
  223. // Set visibility for definitions.
  224. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  225. if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  226. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  227. }
  228. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  229. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  230. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  231. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  232. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  233. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  234. }
  235. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  236. CodeGenOptions::TLSModel M) {
  237. switch (M) {
  238. case CodeGenOptions::GeneralDynamicTLSModel:
  239. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  240. case CodeGenOptions::LocalDynamicTLSModel:
  241. return llvm::GlobalVariable::LocalDynamicTLSModel;
  242. case CodeGenOptions::InitialExecTLSModel:
  243. return llvm::GlobalVariable::InitialExecTLSModel;
  244. case CodeGenOptions::LocalExecTLSModel:
  245. return llvm::GlobalVariable::LocalExecTLSModel;
  246. }
  247. llvm_unreachable("Invalid TLS model!");
  248. }
  249. void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
  250. const VarDecl &D) const {
  251. assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
  252. llvm::GlobalVariable::ThreadLocalMode TLM;
  253. TLM = GetLLVMTLSModel(CodeGenOpts.DefaultTLSModel);
  254. // Override the TLS model if it is explicitly specified.
  255. if (D.hasAttr<TLSModelAttr>()) {
  256. const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
  257. TLM = GetLLVMTLSModel(Attr->getModel());
  258. }
  259. GV->setThreadLocalMode(TLM);
  260. }
  261. /// Set the symbol visibility of type information (vtable and RTTI)
  262. /// associated with the given type.
  263. void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
  264. const CXXRecordDecl *RD,
  265. TypeVisibilityKind TVK) const {
  266. setGlobalVisibility(GV, RD);
  267. if (!CodeGenOpts.HiddenWeakVTables)
  268. return;
  269. // We never want to drop the visibility for RTTI names.
  270. if (TVK == TVK_ForRTTIName)
  271. return;
  272. // We want to drop the visibility to hidden for weak type symbols.
  273. // This isn't possible if there might be unresolved references
  274. // elsewhere that rely on this symbol being visible.
  275. // This should be kept roughly in sync with setThunkVisibility
  276. // in CGVTables.cpp.
  277. // Preconditions.
  278. if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
  279. GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
  280. return;
  281. // Don't override an explicit visibility attribute.
  282. if (RD->getExplicitVisibility())
  283. return;
  284. switch (RD->getTemplateSpecializationKind()) {
  285. // We have to disable the optimization if this is an EI definition
  286. // because there might be EI declarations in other shared objects.
  287. case TSK_ExplicitInstantiationDefinition:
  288. case TSK_ExplicitInstantiationDeclaration:
  289. return;
  290. // Every use of a non-template class's type information has to emit it.
  291. case TSK_Undeclared:
  292. break;
  293. // In theory, implicit instantiations can ignore the possibility of
  294. // an explicit instantiation declaration because there necessarily
  295. // must be an EI definition somewhere with default visibility. In
  296. // practice, it's possible to have an explicit instantiation for
  297. // an arbitrary template class, and linkers aren't necessarily able
  298. // to deal with mixed-visibility symbols.
  299. case TSK_ExplicitSpecialization:
  300. case TSK_ImplicitInstantiation:
  301. if (!CodeGenOpts.HiddenWeakTemplateVTables)
  302. return;
  303. break;
  304. }
  305. // If there's a key function, there may be translation units
  306. // that don't have the key function's definition. But ignore
  307. // this if we're emitting RTTI under -fno-rtti.
  308. if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
  309. if (Context.getKeyFunction(RD))
  310. return;
  311. }
  312. // Otherwise, drop the visibility to hidden.
  313. GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
  314. GV->setUnnamedAddr(true);
  315. }
  316. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  317. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  318. StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
  319. if (!Str.empty())
  320. return Str;
  321. if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  322. IdentifierInfo *II = ND->getIdentifier();
  323. assert(II && "Attempt to mangle unnamed decl.");
  324. Str = II->getName();
  325. return Str;
  326. }
  327. SmallString<256> Buffer;
  328. llvm::raw_svector_ostream Out(Buffer);
  329. if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
  330. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  331. else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
  332. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  333. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
  334. getCXXABI().getMangleContext().mangleBlock(BD, Out,
  335. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
  336. else
  337. getCXXABI().getMangleContext().mangleName(ND, Out);
  338. // Allocate space for the mangled name.
  339. Out.flush();
  340. size_t Length = Buffer.size();
  341. char *Name = MangledNamesAllocator.Allocate<char>(Length);
  342. std::copy(Buffer.begin(), Buffer.end(), Name);
  343. Str = StringRef(Name, Length);
  344. return Str;
  345. }
  346. void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
  347. const BlockDecl *BD) {
  348. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  349. const Decl *D = GD.getDecl();
  350. llvm::raw_svector_ostream Out(Buffer.getBuffer());
  351. if (D == 0)
  352. MangleCtx.mangleGlobalBlock(BD,
  353. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  354. else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  355. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  356. else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
  357. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  358. else
  359. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  360. }
  361. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  362. return getModule().getNamedValue(Name);
  363. }
  364. /// AddGlobalCtor - Add a function to the list that will be called before
  365. /// main() runs.
  366. void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
  367. // FIXME: Type coercion of void()* types.
  368. GlobalCtors.push_back(std::make_pair(Ctor, Priority));
  369. }
  370. /// AddGlobalDtor - Add a function to the list that will be called
  371. /// when the module is unloaded.
  372. void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
  373. // FIXME: Type coercion of void()* types.
  374. GlobalDtors.push_back(std::make_pair(Dtor, Priority));
  375. }
  376. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  377. // Ctor function type is void()*.
  378. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  379. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  380. // Get the type of a ctor entry, { i32, void ()* }.
  381. llvm::StructType *CtorStructTy =
  382. llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
  383. // Construct the constructor and destructor arrays.
  384. SmallVector<llvm::Constant*, 8> Ctors;
  385. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  386. llvm::Constant *S[] = {
  387. llvm::ConstantInt::get(Int32Ty, I->second, false),
  388. llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
  389. };
  390. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  391. }
  392. if (!Ctors.empty()) {
  393. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  394. new llvm::GlobalVariable(TheModule, AT, false,
  395. llvm::GlobalValue::AppendingLinkage,
  396. llvm::ConstantArray::get(AT, Ctors),
  397. GlobalName);
  398. }
  399. }
  400. llvm::GlobalValue::LinkageTypes
  401. CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
  402. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  403. if (Linkage == GVA_Internal)
  404. return llvm::Function::InternalLinkage;
  405. if (D->hasAttr<DLLExportAttr>())
  406. return llvm::Function::DLLExportLinkage;
  407. if (D->hasAttr<WeakAttr>())
  408. return llvm::Function::WeakAnyLinkage;
  409. // In C99 mode, 'inline' functions are guaranteed to have a strong
  410. // definition somewhere else, so we can use available_externally linkage.
  411. if (Linkage == GVA_C99Inline)
  412. return llvm::Function::AvailableExternallyLinkage;
  413. // Note that Apple's kernel linker doesn't support symbol
  414. // coalescing, so we need to avoid linkonce and weak linkages there.
  415. // Normally, this means we just map to internal, but for explicit
  416. // instantiations we'll map to external.
  417. // In C++, the compiler has to emit a definition in every translation unit
  418. // that references the function. We should use linkonce_odr because
  419. // a) if all references in this translation unit are optimized away, we
  420. // don't need to codegen it. b) if the function persists, it needs to be
  421. // merged with other definitions. c) C++ has the ODR, so we know the
  422. // definition is dependable.
  423. if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
  424. return !Context.getLangOpts().AppleKext
  425. ? llvm::Function::LinkOnceODRLinkage
  426. : llvm::Function::InternalLinkage;
  427. // An explicit instantiation of a template has weak linkage, since
  428. // explicit instantiations can occur in multiple translation units
  429. // and must all be equivalent. However, we are not allowed to
  430. // throw away these explicit instantiations.
  431. if (Linkage == GVA_ExplicitTemplateInstantiation)
  432. return !Context.getLangOpts().AppleKext
  433. ? llvm::Function::WeakODRLinkage
  434. : llvm::Function::ExternalLinkage;
  435. // Otherwise, we have strong external linkage.
  436. assert(Linkage == GVA_StrongExternal);
  437. return llvm::Function::ExternalLinkage;
  438. }
  439. /// SetFunctionDefinitionAttributes - Set attributes for a global.
  440. ///
  441. /// FIXME: This is currently only done for aliases and functions, but not for
  442. /// variables (these details are set in EmitGlobalVarDefinition for variables).
  443. void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
  444. llvm::GlobalValue *GV) {
  445. SetCommonAttributes(D, GV);
  446. }
  447. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  448. const CGFunctionInfo &Info,
  449. llvm::Function *F) {
  450. unsigned CallingConv;
  451. AttributeListType AttributeList;
  452. ConstructAttributeList(Info, D, AttributeList, CallingConv);
  453. F->setAttributes(llvm::AttrListPtr::get(AttributeList));
  454. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  455. }
  456. /// Determines whether the language options require us to model
  457. /// unwind exceptions. We treat -fexceptions as mandating this
  458. /// except under the fragile ObjC ABI with only ObjC exceptions
  459. /// enabled. This means, for example, that C with -fexceptions
  460. /// enables this.
  461. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  462. // If exceptions are completely disabled, obviously this is false.
  463. if (!LangOpts.Exceptions) return false;
  464. // If C++ exceptions are enabled, this is true.
  465. if (LangOpts.CXXExceptions) return true;
  466. // If ObjC exceptions are enabled, this depends on the ABI.
  467. if (LangOpts.ObjCExceptions) {
  468. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  469. }
  470. return true;
  471. }
  472. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  473. llvm::Function *F) {
  474. if (CodeGenOpts.UnwindTables)
  475. F->setHasUWTable();
  476. if (!hasUnwindExceptions(LangOpts))
  477. F->addFnAttr(llvm::Attribute::NoUnwind);
  478. if (D->hasAttr<NakedAttr>()) {
  479. // Naked implies noinline: we should not be inlining such functions.
  480. F->addFnAttr(llvm::Attribute::Naked);
  481. F->addFnAttr(llvm::Attribute::NoInline);
  482. }
  483. if (D->hasAttr<NoInlineAttr>())
  484. F->addFnAttr(llvm::Attribute::NoInline);
  485. // (noinline wins over always_inline, and we can't specify both in IR)
  486. if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
  487. !F->hasFnAttr(llvm::Attribute::NoInline))
  488. F->addFnAttr(llvm::Attribute::AlwaysInline);
  489. // FIXME: Communicate hot and cold attributes to LLVM more directly.
  490. if (D->hasAttr<ColdAttr>())
  491. F->addFnAttr(llvm::Attribute::OptimizeForSize);
  492. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  493. F->setUnnamedAddr(true);
  494. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  495. F->addFnAttr(llvm::Attribute::StackProtect);
  496. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  497. F->addFnAttr(llvm::Attribute::StackProtectReq);
  498. if (LangOpts.AddressSanitizer) {
  499. // When AddressSanitizer is enabled, set AddressSafety attribute
  500. // unless __attribute__((no_address_safety_analysis)) is used.
  501. if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
  502. F->addFnAttr(llvm::Attribute::AddressSafety);
  503. }
  504. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  505. if (alignment)
  506. F->setAlignment(alignment);
  507. // C++ ABI requires 2-byte alignment for member functions.
  508. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  509. F->setAlignment(2);
  510. }
  511. void CodeGenModule::SetCommonAttributes(const Decl *D,
  512. llvm::GlobalValue *GV) {
  513. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  514. setGlobalVisibility(GV, ND);
  515. else
  516. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  517. if (D->hasAttr<UsedAttr>())
  518. AddUsedGlobal(GV);
  519. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  520. GV->setSection(SA->getName());
  521. getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
  522. }
  523. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  524. llvm::Function *F,
  525. const CGFunctionInfo &FI) {
  526. SetLLVMFunctionAttributes(D, FI, F);
  527. SetLLVMFunctionAttributesForDefinition(D, F);
  528. F->setLinkage(llvm::Function::InternalLinkage);
  529. SetCommonAttributes(D, F);
  530. }
  531. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  532. llvm::Function *F,
  533. bool IsIncompleteFunction) {
  534. if (unsigned IID = F->getIntrinsicID()) {
  535. // If this is an intrinsic function, set the function's attributes
  536. // to the intrinsic's attributes.
  537. F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
  538. return;
  539. }
  540. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  541. if (!IsIncompleteFunction)
  542. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  543. // Only a few attributes are set on declarations; these may later be
  544. // overridden by a definition.
  545. if (FD->hasAttr<DLLImportAttr>()) {
  546. F->setLinkage(llvm::Function::DLLImportLinkage);
  547. } else if (FD->hasAttr<WeakAttr>() ||
  548. FD->isWeakImported()) {
  549. // "extern_weak" is overloaded in LLVM; we probably should have
  550. // separate linkage types for this.
  551. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  552. } else {
  553. F->setLinkage(llvm::Function::ExternalLinkage);
  554. NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
  555. if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
  556. F->setVisibility(GetLLVMVisibility(LV.visibility()));
  557. }
  558. }
  559. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  560. F->setSection(SA->getName());
  561. }
  562. void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
  563. assert(!GV->isDeclaration() &&
  564. "Only globals with definition can force usage.");
  565. LLVMUsed.push_back(GV);
  566. }
  567. void CodeGenModule::EmitLLVMUsed() {
  568. // Don't create llvm.used if there is no need.
  569. if (LLVMUsed.empty())
  570. return;
  571. // Convert LLVMUsed to what ConstantArray needs.
  572. SmallVector<llvm::Constant*, 8> UsedArray;
  573. UsedArray.resize(LLVMUsed.size());
  574. for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
  575. UsedArray[i] =
  576. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
  577. Int8PtrTy);
  578. }
  579. if (UsedArray.empty())
  580. return;
  581. llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
  582. llvm::GlobalVariable *GV =
  583. new llvm::GlobalVariable(getModule(), ATy, false,
  584. llvm::GlobalValue::AppendingLinkage,
  585. llvm::ConstantArray::get(ATy, UsedArray),
  586. "llvm.used");
  587. GV->setSection("llvm.metadata");
  588. }
  589. void CodeGenModule::EmitDeferred() {
  590. // Emit code for any potentially referenced deferred decls. Since a
  591. // previously unused static decl may become used during the generation of code
  592. // for a static function, iterate until no changes are made.
  593. while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
  594. if (!DeferredVTables.empty()) {
  595. const CXXRecordDecl *RD = DeferredVTables.back();
  596. DeferredVTables.pop_back();
  597. getCXXABI().EmitVTables(RD);
  598. continue;
  599. }
  600. GlobalDecl D = DeferredDeclsToEmit.back();
  601. DeferredDeclsToEmit.pop_back();
  602. // Check to see if we've already emitted this. This is necessary
  603. // for a couple of reasons: first, decls can end up in the
  604. // deferred-decls queue multiple times, and second, decls can end
  605. // up with definitions in unusual ways (e.g. by an extern inline
  606. // function acquiring a strong function redefinition). Just
  607. // ignore these cases.
  608. //
  609. // TODO: That said, looking this up multiple times is very wasteful.
  610. StringRef Name = getMangledName(D);
  611. llvm::GlobalValue *CGRef = GetGlobalValue(Name);
  612. assert(CGRef && "Deferred decl wasn't referenced?");
  613. if (!CGRef->isDeclaration())
  614. continue;
  615. // GlobalAlias::isDeclaration() defers to the aliasee, but for our
  616. // purposes an alias counts as a definition.
  617. if (isa<llvm::GlobalAlias>(CGRef))
  618. continue;
  619. // Otherwise, emit the definition and move on to the next one.
  620. EmitGlobalDefinition(D);
  621. }
  622. }
  623. void CodeGenModule::EmitGlobalAnnotations() {
  624. if (Annotations.empty())
  625. return;
  626. // Create a new global variable for the ConstantStruct in the Module.
  627. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  628. Annotations[0]->getType(), Annotations.size()), Annotations);
  629. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
  630. Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
  631. "llvm.global.annotations");
  632. gv->setSection(AnnotationSection);
  633. }
  634. llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
  635. llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
  636. if (i != AnnotationStrings.end())
  637. return i->second;
  638. // Not found yet, create a new global.
  639. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  640. llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
  641. true, llvm::GlobalValue::PrivateLinkage, s, ".str");
  642. gv->setSection(AnnotationSection);
  643. gv->setUnnamedAddr(true);
  644. AnnotationStrings[Str] = gv;
  645. return gv;
  646. }
  647. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  648. SourceManager &SM = getContext().getSourceManager();
  649. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  650. if (PLoc.isValid())
  651. return EmitAnnotationString(PLoc.getFilename());
  652. return EmitAnnotationString(SM.getBufferName(Loc));
  653. }
  654. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  655. SourceManager &SM = getContext().getSourceManager();
  656. PresumedLoc PLoc = SM.getPresumedLoc(L);
  657. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  658. SM.getExpansionLineNumber(L);
  659. return llvm::ConstantInt::get(Int32Ty, LineNo);
  660. }
  661. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  662. const AnnotateAttr *AA,
  663. SourceLocation L) {
  664. // Get the globals for file name, annotation, and the line number.
  665. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  666. *UnitGV = EmitAnnotationUnit(L),
  667. *LineNoCst = EmitAnnotationLineNo(L);
  668. // Create the ConstantStruct for the global annotation.
  669. llvm::Constant *Fields[4] = {
  670. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  671. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  672. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  673. LineNoCst
  674. };
  675. return llvm::ConstantStruct::getAnon(Fields);
  676. }
  677. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  678. llvm::GlobalValue *GV) {
  679. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  680. // Get the struct elements for these annotations.
  681. for (specific_attr_iterator<AnnotateAttr>
  682. ai = D->specific_attr_begin<AnnotateAttr>(),
  683. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  684. Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
  685. }
  686. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  687. // Never defer when EmitAllDecls is specified.
  688. if (LangOpts.EmitAllDecls)
  689. return false;
  690. return !getContext().DeclMustBeEmitted(Global);
  691. }
  692. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  693. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  694. assert(AA && "No alias?");
  695. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  696. // See if there is already something with the target's name in the module.
  697. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  698. llvm::Constant *Aliasee;
  699. if (isa<llvm::FunctionType>(DeclTy))
  700. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
  701. /*ForVTable=*/false);
  702. else
  703. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  704. llvm::PointerType::getUnqual(DeclTy), 0);
  705. if (!Entry) {
  706. llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
  707. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  708. WeakRefReferences.insert(F);
  709. }
  710. return Aliasee;
  711. }
  712. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  713. const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
  714. // Weak references don't produce any output by themselves.
  715. if (Global->hasAttr<WeakRefAttr>())
  716. return;
  717. // If this is an alias definition (which otherwise looks like a declaration)
  718. // emit it now.
  719. if (Global->hasAttr<AliasAttr>())
  720. return EmitAliasDefinition(GD);
  721. // If this is CUDA, be selective about which declarations we emit.
  722. if (LangOpts.CUDA) {
  723. if (CodeGenOpts.CUDAIsDevice) {
  724. if (!Global->hasAttr<CUDADeviceAttr>() &&
  725. !Global->hasAttr<CUDAGlobalAttr>() &&
  726. !Global->hasAttr<CUDAConstantAttr>() &&
  727. !Global->hasAttr<CUDASharedAttr>())
  728. return;
  729. } else {
  730. if (!Global->hasAttr<CUDAHostAttr>() && (
  731. Global->hasAttr<CUDADeviceAttr>() ||
  732. Global->hasAttr<CUDAConstantAttr>() ||
  733. Global->hasAttr<CUDASharedAttr>()))
  734. return;
  735. }
  736. }
  737. // Ignore declarations, they will be emitted on their first use.
  738. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
  739. // Forward declarations are emitted lazily on first use.
  740. if (!FD->doesThisDeclarationHaveABody()) {
  741. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  742. return;
  743. const FunctionDecl *InlineDefinition = 0;
  744. FD->getBody(InlineDefinition);
  745. StringRef MangledName = getMangledName(GD);
  746. DeferredDecls.erase(MangledName);
  747. EmitGlobalDefinition(InlineDefinition);
  748. return;
  749. }
  750. } else {
  751. const VarDecl *VD = cast<VarDecl>(Global);
  752. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  753. if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
  754. return;
  755. }
  756. // Defer code generation when possible if this is a static definition, inline
  757. // function etc. These we only want to emit if they are used.
  758. if (!MayDeferGeneration(Global)) {
  759. // Emit the definition if it can't be deferred.
  760. EmitGlobalDefinition(GD);
  761. return;
  762. }
  763. // If we're deferring emission of a C++ variable with an
  764. // initializer, remember the order in which it appeared in the file.
  765. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  766. cast<VarDecl>(Global)->hasInit()) {
  767. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  768. CXXGlobalInits.push_back(0);
  769. }
  770. // If the value has already been used, add it directly to the
  771. // DeferredDeclsToEmit list.
  772. StringRef MangledName = getMangledName(GD);
  773. if (GetGlobalValue(MangledName))
  774. DeferredDeclsToEmit.push_back(GD);
  775. else {
  776. // Otherwise, remember that we saw a deferred decl with this name. The
  777. // first use of the mangled name will cause it to move into
  778. // DeferredDeclsToEmit.
  779. DeferredDecls[MangledName] = GD;
  780. }
  781. }
  782. namespace {
  783. struct FunctionIsDirectlyRecursive :
  784. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  785. const StringRef Name;
  786. const Builtin::Context &BI;
  787. bool Result;
  788. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  789. Name(N), BI(C), Result(false) {
  790. }
  791. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  792. bool TraverseCallExpr(CallExpr *E) {
  793. const FunctionDecl *FD = E->getDirectCallee();
  794. if (!FD)
  795. return true;
  796. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  797. if (Attr && Name == Attr->getLabel()) {
  798. Result = true;
  799. return false;
  800. }
  801. unsigned BuiltinID = FD->getBuiltinID();
  802. if (!BuiltinID)
  803. return true;
  804. StringRef BuiltinName = BI.GetName(BuiltinID);
  805. if (BuiltinName.startswith("__builtin_") &&
  806. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  807. Result = true;
  808. return false;
  809. }
  810. return true;
  811. }
  812. };
  813. }
  814. // isTriviallyRecursive - Check if this function calls another
  815. // decl that, because of the asm attribute or the other decl being a builtin,
  816. // ends up pointing to itself.
  817. bool
  818. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  819. StringRef Name;
  820. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  821. // asm labels are a special kind of mangling we have to support.
  822. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  823. if (!Attr)
  824. return false;
  825. Name = Attr->getLabel();
  826. } else {
  827. Name = FD->getName();
  828. }
  829. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  830. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  831. return Walker.Result;
  832. }
  833. bool
  834. CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
  835. if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
  836. return true;
  837. if (CodeGenOpts.OptimizationLevel == 0 &&
  838. !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
  839. return false;
  840. // PR9614. Avoid cases where the source code is lying to us. An available
  841. // externally function should have an equivalent function somewhere else,
  842. // but a function that calls itself is clearly not equivalent to the real
  843. // implementation.
  844. // This happens in glibc's btowc and in some configure checks.
  845. return !isTriviallyRecursive(F);
  846. }
  847. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
  848. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  849. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  850. Context.getSourceManager(),
  851. "Generating code for declaration");
  852. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  853. // At -O0, don't generate IR for functions with available_externally
  854. // linkage.
  855. if (!shouldEmitFunction(Function))
  856. return;
  857. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  858. // Make sure to emit the definition(s) before we emit the thunks.
  859. // This is necessary for the generation of certain thunks.
  860. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
  861. EmitCXXConstructor(CD, GD.getCtorType());
  862. else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
  863. EmitCXXDestructor(DD, GD.getDtorType());
  864. else
  865. EmitGlobalFunctionDefinition(GD);
  866. if (Method->isVirtual())
  867. getVTables().EmitThunks(GD);
  868. return;
  869. }
  870. return EmitGlobalFunctionDefinition(GD);
  871. }
  872. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  873. return EmitGlobalVarDefinition(VD);
  874. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  875. }
  876. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  877. /// module, create and return an llvm Function with the specified type. If there
  878. /// is something in the module with the specified name, return it potentially
  879. /// bitcasted to the right type.
  880. ///
  881. /// If D is non-null, it specifies a decl that correspond to this. This is used
  882. /// to set the attributes on the function when it is first created.
  883. llvm::Constant *
  884. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  885. llvm::Type *Ty,
  886. GlobalDecl D, bool ForVTable,
  887. llvm::Attributes ExtraAttrs) {
  888. // Lookup the entry, lazily creating it if necessary.
  889. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  890. if (Entry) {
  891. if (WeakRefReferences.erase(Entry)) {
  892. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
  893. if (FD && !FD->hasAttr<WeakAttr>())
  894. Entry->setLinkage(llvm::Function::ExternalLinkage);
  895. }
  896. if (Entry->getType()->getElementType() == Ty)
  897. return Entry;
  898. // Make sure the result is of the correct type.
  899. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  900. }
  901. // This function doesn't have a complete type (for example, the return
  902. // type is an incomplete struct). Use a fake type instead, and make
  903. // sure not to try to set attributes.
  904. bool IsIncompleteFunction = false;
  905. llvm::FunctionType *FTy;
  906. if (isa<llvm::FunctionType>(Ty)) {
  907. FTy = cast<llvm::FunctionType>(Ty);
  908. } else {
  909. FTy = llvm::FunctionType::get(VoidTy, false);
  910. IsIncompleteFunction = true;
  911. }
  912. llvm::Function *F = llvm::Function::Create(FTy,
  913. llvm::Function::ExternalLinkage,
  914. MangledName, &getModule());
  915. assert(F->getName() == MangledName && "name was uniqued!");
  916. if (D.getDecl())
  917. SetFunctionAttributes(D, F, IsIncompleteFunction);
  918. if (ExtraAttrs != llvm::Attribute::None)
  919. F->addFnAttr(ExtraAttrs);
  920. // This is the first use or definition of a mangled name. If there is a
  921. // deferred decl with this name, remember that we need to emit it at the end
  922. // of the file.
  923. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  924. if (DDI != DeferredDecls.end()) {
  925. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  926. // list, and remove it from DeferredDecls (since we don't need it anymore).
  927. DeferredDeclsToEmit.push_back(DDI->second);
  928. DeferredDecls.erase(DDI);
  929. // Otherwise, there are cases we have to worry about where we're
  930. // using a declaration for which we must emit a definition but where
  931. // we might not find a top-level definition:
  932. // - member functions defined inline in their classes
  933. // - friend functions defined inline in some class
  934. // - special member functions with implicit definitions
  935. // If we ever change our AST traversal to walk into class methods,
  936. // this will be unnecessary.
  937. //
  938. // We also don't emit a definition for a function if it's going to be an entry
  939. // in a vtable, unless it's already marked as used.
  940. } else if (getLangOpts().CPlusPlus && D.getDecl()) {
  941. // Look for a declaration that's lexically in a record.
  942. const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
  943. FD = FD->getMostRecentDecl();
  944. do {
  945. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  946. if (FD->isImplicit() && !ForVTable) {
  947. assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
  948. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  949. break;
  950. } else if (FD->doesThisDeclarationHaveABody()) {
  951. DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
  952. break;
  953. }
  954. }
  955. FD = FD->getPreviousDecl();
  956. } while (FD);
  957. }
  958. // Make sure the result is of the requested type.
  959. if (!IsIncompleteFunction) {
  960. assert(F->getType()->getElementType() == Ty);
  961. return F;
  962. }
  963. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  964. return llvm::ConstantExpr::getBitCast(F, PTy);
  965. }
  966. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  967. /// non-null, then this function will use the specified type if it has to
  968. /// create it (this occurs when we see a definition of the function).
  969. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  970. llvm::Type *Ty,
  971. bool ForVTable) {
  972. // If there was no specific requested type, just convert it now.
  973. if (!Ty)
  974. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  975. StringRef MangledName = getMangledName(GD);
  976. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
  977. }
  978. /// CreateRuntimeFunction - Create a new runtime function with the specified
  979. /// type and name.
  980. llvm::Constant *
  981. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  982. StringRef Name,
  983. llvm::Attributes ExtraAttrs) {
  984. return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  985. ExtraAttrs);
  986. }
  987. /// isTypeConstant - Determine whether an object of this type can be emitted
  988. /// as a constant.
  989. ///
  990. /// If ExcludeCtor is true, the duration when the object's constructor runs
  991. /// will not be considered. The caller will need to verify that the object is
  992. /// not written to during its construction.
  993. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  994. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  995. return false;
  996. if (Context.getLangOpts().CPlusPlus) {
  997. if (const CXXRecordDecl *Record
  998. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  999. return ExcludeCtor && !Record->hasMutableFields() &&
  1000. Record->hasTrivialDestructor();
  1001. }
  1002. return true;
  1003. }
  1004. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1005. /// create and return an llvm GlobalVariable with the specified type. If there
  1006. /// is something in the module with the specified name, return it potentially
  1007. /// bitcasted to the right type.
  1008. ///
  1009. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1010. /// to set the attributes on the global when it is first created.
  1011. llvm::Constant *
  1012. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1013. llvm::PointerType *Ty,
  1014. const VarDecl *D,
  1015. bool UnnamedAddr) {
  1016. // Lookup the entry, lazily creating it if necessary.
  1017. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1018. if (Entry) {
  1019. if (WeakRefReferences.erase(Entry)) {
  1020. if (D && !D->hasAttr<WeakAttr>())
  1021. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1022. }
  1023. if (UnnamedAddr)
  1024. Entry->setUnnamedAddr(true);
  1025. if (Entry->getType() == Ty)
  1026. return Entry;
  1027. // Make sure the result is of the correct type.
  1028. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1029. }
  1030. // This is the first use or definition of a mangled name. If there is a
  1031. // deferred decl with this name, remember that we need to emit it at the end
  1032. // of the file.
  1033. llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
  1034. if (DDI != DeferredDecls.end()) {
  1035. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1036. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1037. DeferredDeclsToEmit.push_back(DDI->second);
  1038. DeferredDecls.erase(DDI);
  1039. }
  1040. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1041. llvm::GlobalVariable *GV =
  1042. new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
  1043. llvm::GlobalValue::ExternalLinkage,
  1044. 0, MangledName, 0,
  1045. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1046. // Handle things which are present even on external declarations.
  1047. if (D) {
  1048. // FIXME: This code is overly simple and should be merged with other global
  1049. // handling.
  1050. GV->setConstant(isTypeConstant(D->getType(), false));
  1051. // Set linkage and visibility in case we never see a definition.
  1052. NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
  1053. if (LV.linkage() != ExternalLinkage) {
  1054. // Don't set internal linkage on declarations.
  1055. } else {
  1056. if (D->hasAttr<DLLImportAttr>())
  1057. GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
  1058. else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
  1059. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1060. // Set visibility on a declaration only if it's explicit.
  1061. if (LV.visibilityExplicit())
  1062. GV->setVisibility(GetLLVMVisibility(LV.visibility()));
  1063. }
  1064. if (D->isThreadSpecified())
  1065. setTLSMode(GV, *D);
  1066. }
  1067. if (AddrSpace != Ty->getAddressSpace())
  1068. return llvm::ConstantExpr::getBitCast(GV, Ty);
  1069. else
  1070. return GV;
  1071. }
  1072. llvm::GlobalVariable *
  1073. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1074. llvm::Type *Ty,
  1075. llvm::GlobalValue::LinkageTypes Linkage) {
  1076. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1077. llvm::GlobalVariable *OldGV = 0;
  1078. if (GV) {
  1079. // Check if the variable has the right type.
  1080. if (GV->getType()->getElementType() == Ty)
  1081. return GV;
  1082. // Because C++ name mangling, the only way we can end up with an already
  1083. // existing global with the same name is if it has been declared extern "C".
  1084. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1085. OldGV = GV;
  1086. }
  1087. // Create a new variable.
  1088. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1089. Linkage, 0, Name);
  1090. if (OldGV) {
  1091. // Replace occurrences of the old variable if needed.
  1092. GV->takeName(OldGV);
  1093. if (!OldGV->use_empty()) {
  1094. llvm::Constant *NewPtrForOldDecl =
  1095. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1096. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1097. }
  1098. OldGV->eraseFromParent();
  1099. }
  1100. return GV;
  1101. }
  1102. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1103. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1104. /// then it will be created with the specified type instead of whatever the
  1105. /// normal requested type would be.
  1106. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1107. llvm::Type *Ty) {
  1108. assert(D->hasGlobalStorage() && "Not a global variable");
  1109. QualType ASTTy = D->getType();
  1110. if (Ty == 0)
  1111. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1112. llvm::PointerType *PTy =
  1113. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1114. StringRef MangledName = getMangledName(D);
  1115. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1116. }
  1117. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1118. /// specified type and name.
  1119. llvm::Constant *
  1120. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1121. StringRef Name) {
  1122. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
  1123. true);
  1124. }
  1125. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1126. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1127. if (MayDeferGeneration(D)) {
  1128. // If we have not seen a reference to this variable yet, place it
  1129. // into the deferred declarations table to be emitted if needed
  1130. // later.
  1131. StringRef MangledName = getMangledName(D);
  1132. if (!GetGlobalValue(MangledName)) {
  1133. DeferredDecls[MangledName] = D;
  1134. return;
  1135. }
  1136. }
  1137. // The tentative definition is the only definition.
  1138. EmitGlobalVarDefinition(D);
  1139. }
  1140. void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
  1141. if (DefinitionRequired)
  1142. getCXXABI().EmitVTables(Class);
  1143. }
  1144. llvm::GlobalVariable::LinkageTypes
  1145. CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
  1146. if (RD->getLinkage() != ExternalLinkage)
  1147. return llvm::GlobalVariable::InternalLinkage;
  1148. if (const CXXMethodDecl *KeyFunction
  1149. = RD->getASTContext().getKeyFunction(RD)) {
  1150. // If this class has a key function, use that to determine the linkage of
  1151. // the vtable.
  1152. const FunctionDecl *Def = 0;
  1153. if (KeyFunction->hasBody(Def))
  1154. KeyFunction = cast<CXXMethodDecl>(Def);
  1155. switch (KeyFunction->getTemplateSpecializationKind()) {
  1156. case TSK_Undeclared:
  1157. case TSK_ExplicitSpecialization:
  1158. // When compiling with optimizations turned on, we emit all vtables,
  1159. // even if the key function is not defined in the current translation
  1160. // unit. If this is the case, use available_externally linkage.
  1161. if (!Def && CodeGenOpts.OptimizationLevel)
  1162. return llvm::GlobalVariable::AvailableExternallyLinkage;
  1163. if (KeyFunction->isInlined())
  1164. return !Context.getLangOpts().AppleKext ?
  1165. llvm::GlobalVariable::LinkOnceODRLinkage :
  1166. llvm::Function::InternalLinkage;
  1167. return llvm::GlobalVariable::ExternalLinkage;
  1168. case TSK_ImplicitInstantiation:
  1169. return !Context.getLangOpts().AppleKext ?
  1170. llvm::GlobalVariable::LinkOnceODRLinkage :
  1171. llvm::Function::InternalLinkage;
  1172. case TSK_ExplicitInstantiationDefinition:
  1173. return !Context.getLangOpts().AppleKext ?
  1174. llvm::GlobalVariable::WeakODRLinkage :
  1175. llvm::Function::InternalLinkage;
  1176. case TSK_ExplicitInstantiationDeclaration:
  1177. // FIXME: Use available_externally linkage. However, this currently
  1178. // breaks LLVM's build due to undefined symbols.
  1179. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1180. return !Context.getLangOpts().AppleKext ?
  1181. llvm::GlobalVariable::LinkOnceODRLinkage :
  1182. llvm::Function::InternalLinkage;
  1183. }
  1184. }
  1185. if (Context.getLangOpts().AppleKext)
  1186. return llvm::Function::InternalLinkage;
  1187. switch (RD->getTemplateSpecializationKind()) {
  1188. case TSK_Undeclared:
  1189. case TSK_ExplicitSpecialization:
  1190. case TSK_ImplicitInstantiation:
  1191. // FIXME: Use available_externally linkage. However, this currently
  1192. // breaks LLVM's build due to undefined symbols.
  1193. // return llvm::GlobalVariable::AvailableExternallyLinkage;
  1194. case TSK_ExplicitInstantiationDeclaration:
  1195. return llvm::GlobalVariable::LinkOnceODRLinkage;
  1196. case TSK_ExplicitInstantiationDefinition:
  1197. return llvm::GlobalVariable::WeakODRLinkage;
  1198. }
  1199. llvm_unreachable("Invalid TemplateSpecializationKind!");
  1200. }
  1201. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1202. return Context.toCharUnitsFromBits(
  1203. TheTargetData.getTypeStoreSizeInBits(Ty));
  1204. }
  1205. llvm::Constant *
  1206. CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
  1207. const Expr *rawInit) {
  1208. ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
  1209. if (const ExprWithCleanups *withCleanups =
  1210. dyn_cast<ExprWithCleanups>(rawInit)) {
  1211. cleanups = withCleanups->getObjects();
  1212. rawInit = withCleanups->getSubExpr();
  1213. }
  1214. const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
  1215. if (!init || !init->initializesStdInitializerList() ||
  1216. init->getNumInits() == 0)
  1217. return 0;
  1218. ASTContext &ctx = getContext();
  1219. unsigned numInits = init->getNumInits();
  1220. // FIXME: This check is here because we would otherwise silently miscompile
  1221. // nested global std::initializer_lists. Better would be to have a real
  1222. // implementation.
  1223. for (unsigned i = 0; i < numInits; ++i) {
  1224. const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
  1225. if (inner && inner->initializesStdInitializerList()) {
  1226. ErrorUnsupported(inner, "nested global std::initializer_list");
  1227. return 0;
  1228. }
  1229. }
  1230. // Synthesize a fake VarDecl for the array and initialize that.
  1231. QualType elementType = init->getInit(0)->getType();
  1232. llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
  1233. QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
  1234. ArrayType::Normal, 0);
  1235. IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
  1236. TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
  1237. arrayType, D->getLocation());
  1238. VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
  1239. D->getDeclContext()),
  1240. D->getLocStart(), D->getLocation(),
  1241. name, arrayType, sourceInfo,
  1242. SC_Static, SC_Static);
  1243. // Now clone the InitListExpr to initialize the array instead.
  1244. // Incredible hack: we want to use the existing InitListExpr here, so we need
  1245. // to tell it that it no longer initializes a std::initializer_list.
  1246. ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
  1247. init->getNumInits());
  1248. Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
  1249. init->getRBraceLoc());
  1250. arrayInit->setType(arrayType);
  1251. if (!cleanups.empty())
  1252. arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
  1253. backingArray->setInit(arrayInit);
  1254. // Emit the definition of the array.
  1255. EmitGlobalVarDefinition(backingArray);
  1256. // Inspect the initializer list to validate it and determine its type.
  1257. // FIXME: doing this every time is probably inefficient; caching would be nice
  1258. RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
  1259. RecordDecl::field_iterator field = record->field_begin();
  1260. if (field == record->field_end()) {
  1261. ErrorUnsupported(D, "weird std::initializer_list");
  1262. return 0;
  1263. }
  1264. QualType elementPtr = ctx.getPointerType(elementType.withConst());
  1265. // Start pointer.
  1266. if (!ctx.hasSameType(field->getType(), elementPtr)) {
  1267. ErrorUnsupported(D, "weird std::initializer_list");
  1268. return 0;
  1269. }
  1270. ++field;
  1271. if (field == record->field_end()) {
  1272. ErrorUnsupported(D, "weird std::initializer_list");
  1273. return 0;
  1274. }
  1275. bool isStartEnd = false;
  1276. if (ctx.hasSameType(field->getType(), elementPtr)) {
  1277. // End pointer.
  1278. isStartEnd = true;
  1279. } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
  1280. ErrorUnsupported(D, "weird std::initializer_list");
  1281. return 0;
  1282. }
  1283. // Now build an APValue representing the std::initializer_list.
  1284. APValue initListValue(APValue::UninitStruct(), 0, 2);
  1285. APValue &startField = initListValue.getStructField(0);
  1286. APValue::LValuePathEntry startOffsetPathEntry;
  1287. startOffsetPathEntry.ArrayIndex = 0;
  1288. startField = APValue(APValue::LValueBase(backingArray),
  1289. CharUnits::fromQuantity(0),
  1290. llvm::makeArrayRef(startOffsetPathEntry),
  1291. /*IsOnePastTheEnd=*/false, 0);
  1292. if (isStartEnd) {
  1293. APValue &endField = initListValue.getStructField(1);
  1294. APValue::LValuePathEntry endOffsetPathEntry;
  1295. endOffsetPathEntry.ArrayIndex = numInits;
  1296. endField = APValue(APValue::LValueBase(backingArray),
  1297. ctx.getTypeSizeInChars(elementType) * numInits,
  1298. llvm::makeArrayRef(endOffsetPathEntry),
  1299. /*IsOnePastTheEnd=*/true, 0);
  1300. } else {
  1301. APValue &sizeField = initListValue.getStructField(1);
  1302. sizeField = APValue(llvm::APSInt(numElements));
  1303. }
  1304. // Emit the constant for the initializer_list.
  1305. llvm::Constant *llvmInit =
  1306. EmitConstantValueForMemory(initListValue, D->getType());
  1307. assert(llvmInit && "failed to initialize as constant");
  1308. return llvmInit;
  1309. }
  1310. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1311. unsigned AddrSpace) {
  1312. if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
  1313. if (D->hasAttr<CUDAConstantAttr>())
  1314. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1315. else if (D->hasAttr<CUDASharedAttr>())
  1316. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1317. else
  1318. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1319. }
  1320. return AddrSpace;
  1321. }
  1322. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1323. llvm::Constant *Init = 0;
  1324. QualType ASTTy = D->getType();
  1325. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1326. bool NeedsGlobalCtor = false;
  1327. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1328. const VarDecl *InitDecl;
  1329. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1330. if (!InitExpr) {
  1331. // This is a tentative definition; tentative definitions are
  1332. // implicitly initialized with { 0 }.
  1333. //
  1334. // Note that tentative definitions are only emitted at the end of
  1335. // a translation unit, so they should never have incomplete
  1336. // type. In addition, EmitTentativeDefinition makes sure that we
  1337. // never attempt to emit a tentative definition if a real one
  1338. // exists. A use may still exists, however, so we still may need
  1339. // to do a RAUW.
  1340. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1341. Init = EmitNullConstant(D->getType());
  1342. } else {
  1343. // If this is a std::initializer_list, emit the special initializer.
  1344. Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
  1345. // An empty init list will perform zero-initialization, which happens
  1346. // to be exactly what we want.
  1347. // FIXME: It does so in a global constructor, which is *not* what we
  1348. // want.
  1349. if (!Init) {
  1350. initializedGlobalDecl = GlobalDecl(D);
  1351. Init = EmitConstantInit(*InitDecl);
  1352. }
  1353. if (!Init) {
  1354. QualType T = InitExpr->getType();
  1355. if (D->getType()->isReferenceType())
  1356. T = D->getType();
  1357. if (getLangOpts().CPlusPlus) {
  1358. Init = EmitNullConstant(T);
  1359. NeedsGlobalCtor = true;
  1360. } else {
  1361. ErrorUnsupported(D, "static initializer");
  1362. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1363. }
  1364. } else {
  1365. // We don't need an initializer, so remove the entry for the delayed
  1366. // initializer position (just in case this entry was delayed) if we
  1367. // also don't need to register a destructor.
  1368. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1369. DelayedCXXInitPosition.erase(D);
  1370. }
  1371. }
  1372. llvm::Type* InitType = Init->getType();
  1373. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1374. // Strip off a bitcast if we got one back.
  1375. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1376. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1377. // all zero index gep.
  1378. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1379. Entry = CE->getOperand(0);
  1380. }
  1381. // Entry is now either a Function or GlobalVariable.
  1382. llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1383. // We have a definition after a declaration with the wrong type.
  1384. // We must make a new GlobalVariable* and update everything that used OldGV
  1385. // (a declaration or tentative definition) with the new GlobalVariable*
  1386. // (which will be a definition).
  1387. //
  1388. // This happens if there is a prototype for a global (e.g.
  1389. // "extern int x[];") and then a definition of a different type (e.g.
  1390. // "int x[10];"). This also happens when an initializer has a different type
  1391. // from the type of the global (this happens with unions).
  1392. if (GV == 0 ||
  1393. GV->getType()->getElementType() != InitType ||
  1394. GV->getType()->getAddressSpace() !=
  1395. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1396. // Move the old entry aside so that we'll create a new one.
  1397. Entry->setName(StringRef());
  1398. // Make a new global with the correct type, this is now guaranteed to work.
  1399. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1400. // Replace all uses of the old global with the new global
  1401. llvm::Constant *NewPtrForOldDecl =
  1402. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1403. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1404. // Erase the old global, since it is no longer used.
  1405. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1406. }
  1407. if (D->hasAttr<AnnotateAttr>())
  1408. AddGlobalAnnotations(D, GV);
  1409. GV->setInitializer(Init);
  1410. // If it is safe to mark the global 'constant', do so now.
  1411. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1412. isTypeConstant(D->getType(), true));
  1413. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1414. // Set the llvm linkage type as appropriate.
  1415. llvm::GlobalValue::LinkageTypes Linkage =
  1416. GetLLVMLinkageVarDefinition(D, GV);
  1417. GV->setLinkage(Linkage);
  1418. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1419. // common vars aren't constant even if declared const.
  1420. GV->setConstant(false);
  1421. SetCommonAttributes(D, GV);
  1422. // Emit the initializer function if necessary.
  1423. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1424. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1425. // If we are compiling with ASan, add metadata indicating dynamically
  1426. // initialized globals.
  1427. if (LangOpts.AddressSanitizer && NeedsGlobalCtor) {
  1428. llvm::Module &M = getModule();
  1429. llvm::NamedMDNode *DynamicInitializers =
  1430. M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
  1431. llvm::Value *GlobalToAdd[] = { GV };
  1432. llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
  1433. DynamicInitializers->addOperand(ThisGlobal);
  1434. }
  1435. // Emit global variable debug information.
  1436. if (CGDebugInfo *DI = getModuleDebugInfo())
  1437. if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo)
  1438. DI->EmitGlobalVariable(GV, D);
  1439. }
  1440. llvm::GlobalValue::LinkageTypes
  1441. CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
  1442. llvm::GlobalVariable *GV) {
  1443. GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
  1444. if (Linkage == GVA_Internal)
  1445. return llvm::Function::InternalLinkage;
  1446. else if (D->hasAttr<DLLImportAttr>())
  1447. return llvm::Function::DLLImportLinkage;
  1448. else if (D->hasAttr<DLLExportAttr>())
  1449. return llvm::Function::DLLExportLinkage;
  1450. else if (D->hasAttr<WeakAttr>()) {
  1451. if (GV->isConstant())
  1452. return llvm::GlobalVariable::WeakODRLinkage;
  1453. else
  1454. return llvm::GlobalVariable::WeakAnyLinkage;
  1455. } else if (Linkage == GVA_TemplateInstantiation ||
  1456. Linkage == GVA_ExplicitTemplateInstantiation)
  1457. return llvm::GlobalVariable::WeakODRLinkage;
  1458. else if (!getLangOpts().CPlusPlus &&
  1459. ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
  1460. D->getAttr<CommonAttr>()) &&
  1461. !D->hasExternalStorage() && !D->getInit() &&
  1462. !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
  1463. !D->getAttr<WeakImportAttr>()) {
  1464. // Thread local vars aren't considered common linkage.
  1465. return llvm::GlobalVariable::CommonLinkage;
  1466. }
  1467. return llvm::GlobalVariable::ExternalLinkage;
  1468. }
  1469. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1470. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1471. /// existing call uses of the old function in the module, this adjusts them to
  1472. /// call the new function directly.
  1473. ///
  1474. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1475. /// functions to be able to inline them. If there is a bitcast in the way, it
  1476. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1477. /// run at -O0.
  1478. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1479. llvm::Function *NewFn) {
  1480. // If we're redefining a global as a function, don't transform it.
  1481. llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
  1482. if (OldFn == 0) return;
  1483. llvm::Type *NewRetTy = NewFn->getReturnType();
  1484. SmallVector<llvm::Value*, 4> ArgList;
  1485. for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
  1486. UI != E; ) {
  1487. // TODO: Do invokes ever occur in C code? If so, we should handle them too.
  1488. llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
  1489. llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
  1490. if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
  1491. llvm::CallSite CS(CI);
  1492. if (!CI || !CS.isCallee(I)) continue;
  1493. // If the return types don't match exactly, and if the call isn't dead, then
  1494. // we can't transform this call.
  1495. if (CI->getType() != NewRetTy && !CI->use_empty())
  1496. continue;
  1497. // Get the attribute list.
  1498. llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
  1499. llvm::AttrListPtr AttrList = CI->getAttributes();
  1500. // Get any return attributes.
  1501. llvm::Attributes RAttrs = AttrList.getRetAttributes();
  1502. // Add the return attributes.
  1503. if (RAttrs)
  1504. AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
  1505. // If the function was passed too few arguments, don't transform. If extra
  1506. // arguments were passed, we silently drop them. If any of the types
  1507. // mismatch, we don't transform.
  1508. unsigned ArgNo = 0;
  1509. bool DontTransform = false;
  1510. for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
  1511. E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
  1512. if (CS.arg_size() == ArgNo ||
  1513. CS.getArgument(ArgNo)->getType() != AI->getType()) {
  1514. DontTransform = true;
  1515. break;
  1516. }
  1517. // Add any parameter attributes.
  1518. if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
  1519. AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
  1520. }
  1521. if (DontTransform)
  1522. continue;
  1523. if (llvm::Attributes FnAttrs = AttrList.getFnAttributes())
  1524. AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
  1525. // Okay, we can transform this. Create the new call instruction and copy
  1526. // over the required information.
  1527. ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
  1528. llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
  1529. ArgList.clear();
  1530. if (!NewCall->getType()->isVoidTy())
  1531. NewCall->takeName(CI);
  1532. NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec));
  1533. NewCall->setCallingConv(CI->getCallingConv());
  1534. // Finally, remove the old call, replacing any uses with the new one.
  1535. if (!CI->use_empty())
  1536. CI->replaceAllUsesWith(NewCall);
  1537. // Copy debug location attached to CI.
  1538. if (!CI->getDebugLoc().isUnknown())
  1539. NewCall->setDebugLoc(CI->getDebugLoc());
  1540. CI->eraseFromParent();
  1541. }
  1542. }
  1543. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1544. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1545. // If we have a definition, this might be a deferred decl. If the
  1546. // instantiation is explicit, make sure we emit it at the end.
  1547. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1548. GetAddrOfGlobalVar(VD);
  1549. }
  1550. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
  1551. const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
  1552. // Compute the function info and LLVM type.
  1553. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1554. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1555. // Get or create the prototype for the function.
  1556. llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
  1557. // Strip off a bitcast if we got one back.
  1558. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1559. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1560. Entry = CE->getOperand(0);
  1561. }
  1562. if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
  1563. llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
  1564. // If the types mismatch then we have to rewrite the definition.
  1565. assert(OldFn->isDeclaration() &&
  1566. "Shouldn't replace non-declaration");
  1567. // F is the Function* for the one with the wrong type, we must make a new
  1568. // Function* and update everything that used F (a declaration) with the new
  1569. // Function* (which will be a definition).
  1570. //
  1571. // This happens if there is a prototype for a function
  1572. // (e.g. "int f()") and then a definition of a different type
  1573. // (e.g. "int f(int x)"). Move the old function aside so that it
  1574. // doesn't interfere with GetAddrOfFunction.
  1575. OldFn->setName(StringRef());
  1576. llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1577. // If this is an implementation of a function without a prototype, try to
  1578. // replace any existing uses of the function (which may be calls) with uses
  1579. // of the new function
  1580. if (D->getType()->isFunctionNoProtoType()) {
  1581. ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
  1582. OldFn->removeDeadConstantUsers();
  1583. }
  1584. // Replace uses of F with the Function we will endow with a body.
  1585. if (!Entry->use_empty()) {
  1586. llvm::Constant *NewPtrForOldDecl =
  1587. llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
  1588. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1589. }
  1590. // Ok, delete the old function now, which is dead.
  1591. OldFn->eraseFromParent();
  1592. Entry = NewFn;
  1593. }
  1594. // We need to set linkage and visibility on the function before
  1595. // generating code for it because various parts of IR generation
  1596. // want to propagate this information down (e.g. to local static
  1597. // declarations).
  1598. llvm::Function *Fn = cast<llvm::Function>(Entry);
  1599. setFunctionLinkage(D, Fn);
  1600. // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
  1601. setGlobalVisibility(Fn, D);
  1602. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1603. SetFunctionDefinitionAttributes(D, Fn);
  1604. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1605. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1606. AddGlobalCtor(Fn, CA->getPriority());
  1607. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1608. AddGlobalDtor(Fn, DA->getPriority());
  1609. if (D->hasAttr<AnnotateAttr>())
  1610. AddGlobalAnnotations(D, Fn);
  1611. }
  1612. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1613. const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
  1614. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1615. assert(AA && "Not an alias?");
  1616. StringRef MangledName = getMangledName(GD);
  1617. // If there is a definition in the module, then it wins over the alias.
  1618. // This is dubious, but allow it to be safe. Just ignore the alias.
  1619. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1620. if (Entry && !Entry->isDeclaration())
  1621. return;
  1622. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1623. // Create a reference to the named value. This ensures that it is emitted
  1624. // if a deferred decl.
  1625. llvm::Constant *Aliasee;
  1626. if (isa<llvm::FunctionType>(DeclTy))
  1627. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
  1628. /*ForVTable=*/false);
  1629. else
  1630. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1631. llvm::PointerType::getUnqual(DeclTy), 0);
  1632. // Create the new alias itself, but don't set a name yet.
  1633. llvm::GlobalValue *GA =
  1634. new llvm::GlobalAlias(Aliasee->getType(),
  1635. llvm::Function::ExternalLinkage,
  1636. "", Aliasee, &getModule());
  1637. if (Entry) {
  1638. assert(Entry->isDeclaration());
  1639. // If there is a declaration in the module, then we had an extern followed
  1640. // by the alias, as in:
  1641. // extern int test6();
  1642. // ...
  1643. // int test6() __attribute__((alias("test7")));
  1644. //
  1645. // Remove it and replace uses of it with the alias.
  1646. GA->takeName(Entry);
  1647. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1648. Entry->getType()));
  1649. Entry->eraseFromParent();
  1650. } else {
  1651. GA->setName(MangledName);
  1652. }
  1653. // Set attributes which are particular to an alias; this is a
  1654. // specialization of the attributes which may be set on a global
  1655. // variable/function.
  1656. if (D->hasAttr<DLLExportAttr>()) {
  1657. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1658. // The dllexport attribute is ignored for undefined symbols.
  1659. if (FD->hasBody())
  1660. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1661. } else {
  1662. GA->setLinkage(llvm::Function::DLLExportLinkage);
  1663. }
  1664. } else if (D->hasAttr<WeakAttr>() ||
  1665. D->hasAttr<WeakRefAttr>() ||
  1666. D->isWeakImported()) {
  1667. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  1668. }
  1669. SetCommonAttributes(D, GA);
  1670. }
  1671. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  1672. ArrayRef<llvm::Type*> Tys) {
  1673. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  1674. Tys);
  1675. }
  1676. static llvm::StringMapEntry<llvm::Constant*> &
  1677. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1678. const StringLiteral *Literal,
  1679. bool TargetIsLSB,
  1680. bool &IsUTF16,
  1681. unsigned &StringLength) {
  1682. StringRef String = Literal->getString();
  1683. unsigned NumBytes = String.size();
  1684. // Check for simple case.
  1685. if (!Literal->containsNonAsciiOrNull()) {
  1686. StringLength = NumBytes;
  1687. return Map.GetOrCreateValue(String);
  1688. }
  1689. // Otherwise, convert the UTF8 literals into a string of shorts.
  1690. IsUTF16 = true;
  1691. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  1692. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1693. UTF16 *ToPtr = &ToBuf[0];
  1694. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1695. &ToPtr, ToPtr + NumBytes,
  1696. strictConversion);
  1697. // ConvertUTF8toUTF16 returns the length in ToPtr.
  1698. StringLength = ToPtr - &ToBuf[0];
  1699. // Add an explicit null.
  1700. *ToPtr = 0;
  1701. return Map.
  1702. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  1703. (StringLength + 1) * 2));
  1704. }
  1705. static llvm::StringMapEntry<llvm::Constant*> &
  1706. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  1707. const StringLiteral *Literal,
  1708. unsigned &StringLength) {
  1709. StringRef String = Literal->getString();
  1710. StringLength = String.size();
  1711. return Map.GetOrCreateValue(String);
  1712. }
  1713. llvm::Constant *
  1714. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  1715. unsigned StringLength = 0;
  1716. bool isUTF16 = false;
  1717. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1718. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  1719. getTargetData().isLittleEndian(),
  1720. isUTF16, StringLength);
  1721. if (llvm::Constant *C = Entry.getValue())
  1722. return C;
  1723. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1724. llvm::Constant *Zeros[] = { Zero, Zero };
  1725. // If we don't already have it, get __CFConstantStringClassReference.
  1726. if (!CFConstantStringClassRef) {
  1727. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1728. Ty = llvm::ArrayType::get(Ty, 0);
  1729. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  1730. "__CFConstantStringClassReference");
  1731. // Decay array -> ptr
  1732. CFConstantStringClassRef =
  1733. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1734. }
  1735. QualType CFTy = getContext().getCFConstantStringType();
  1736. llvm::StructType *STy =
  1737. cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  1738. llvm::Constant *Fields[4];
  1739. // Class pointer.
  1740. Fields[0] = CFConstantStringClassRef;
  1741. // Flags.
  1742. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1743. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  1744. llvm::ConstantInt::get(Ty, 0x07C8);
  1745. // String pointer.
  1746. llvm::Constant *C = 0;
  1747. if (isUTF16) {
  1748. ArrayRef<uint16_t> Arr =
  1749. llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
  1750. Entry.getKey().size() / 2);
  1751. C = llvm::ConstantDataArray::get(VMContext, Arr);
  1752. } else {
  1753. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1754. }
  1755. llvm::GlobalValue::LinkageTypes Linkage;
  1756. if (isUTF16)
  1757. // FIXME: why do utf strings get "_" labels instead of "L" labels?
  1758. Linkage = llvm::GlobalValue::InternalLinkage;
  1759. else
  1760. // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
  1761. // when using private linkage. It is not clear if this is a bug in ld
  1762. // or a reasonable new restriction.
  1763. Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
  1764. // Note: -fwritable-strings doesn't make the backing store strings of
  1765. // CFStrings writable. (See <rdar://problem/10657500>)
  1766. llvm::GlobalVariable *GV =
  1767. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  1768. Linkage, C, ".str");
  1769. GV->setUnnamedAddr(true);
  1770. if (isUTF16) {
  1771. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  1772. GV->setAlignment(Align.getQuantity());
  1773. } else {
  1774. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1775. GV->setAlignment(Align.getQuantity());
  1776. }
  1777. // String.
  1778. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1779. if (isUTF16)
  1780. // Cast the UTF16 string to the correct type.
  1781. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  1782. // String length.
  1783. Ty = getTypes().ConvertType(getContext().LongTy);
  1784. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  1785. // The struct.
  1786. C = llvm::ConstantStruct::get(STy, Fields);
  1787. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1788. llvm::GlobalVariable::PrivateLinkage, C,
  1789. "_unnamed_cfstring_");
  1790. if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
  1791. GV->setSection(Sect);
  1792. Entry.setValue(GV);
  1793. return GV;
  1794. }
  1795. static RecordDecl *
  1796. CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
  1797. DeclContext *DC, IdentifierInfo *Id) {
  1798. SourceLocation Loc;
  1799. if (Ctx.getLangOpts().CPlusPlus)
  1800. return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1801. else
  1802. return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
  1803. }
  1804. llvm::Constant *
  1805. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  1806. unsigned StringLength = 0;
  1807. llvm::StringMapEntry<llvm::Constant*> &Entry =
  1808. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  1809. if (llvm::Constant *C = Entry.getValue())
  1810. return C;
  1811. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  1812. llvm::Constant *Zeros[] = { Zero, Zero };
  1813. // If we don't already have it, get _NSConstantStringClassReference.
  1814. if (!ConstantStringClassRef) {
  1815. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  1816. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  1817. llvm::Constant *GV;
  1818. if (LangOpts.ObjCRuntime.isNonFragile()) {
  1819. std::string str =
  1820. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  1821. : "OBJC_CLASS_$_" + StringClass;
  1822. GV = getObjCRuntime().GetClassGlobal(str);
  1823. // Make sure the result is of the correct type.
  1824. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1825. ConstantStringClassRef =
  1826. llvm::ConstantExpr::getBitCast(GV, PTy);
  1827. } else {
  1828. std::string str =
  1829. StringClass.empty() ? "_NSConstantStringClassReference"
  1830. : "_" + StringClass + "ClassReference";
  1831. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  1832. GV = CreateRuntimeVariable(PTy, str);
  1833. // Decay array -> ptr
  1834. ConstantStringClassRef =
  1835. llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1836. }
  1837. }
  1838. if (!NSConstantStringType) {
  1839. // Construct the type for a constant NSString.
  1840. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1841. Context.getTranslationUnitDecl(),
  1842. &Context.Idents.get("__builtin_NSString"));
  1843. D->startDefinition();
  1844. QualType FieldTypes[3];
  1845. // const int *isa;
  1846. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  1847. // const char *str;
  1848. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  1849. // unsigned int length;
  1850. FieldTypes[2] = Context.UnsignedIntTy;
  1851. // Create fields
  1852. for (unsigned i = 0; i < 3; ++i) {
  1853. FieldDecl *Field = FieldDecl::Create(Context, D,
  1854. SourceLocation(),
  1855. SourceLocation(), 0,
  1856. FieldTypes[i], /*TInfo=*/0,
  1857. /*BitWidth=*/0,
  1858. /*Mutable=*/false,
  1859. ICIS_NoInit);
  1860. Field->setAccess(AS_public);
  1861. D->addDecl(Field);
  1862. }
  1863. D->completeDefinition();
  1864. QualType NSTy = Context.getTagDeclType(D);
  1865. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  1866. }
  1867. llvm::Constant *Fields[3];
  1868. // Class pointer.
  1869. Fields[0] = ConstantStringClassRef;
  1870. // String pointer.
  1871. llvm::Constant *C =
  1872. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  1873. llvm::GlobalValue::LinkageTypes Linkage;
  1874. bool isConstant;
  1875. Linkage = llvm::GlobalValue::PrivateLinkage;
  1876. isConstant = !LangOpts.WritableStrings;
  1877. llvm::GlobalVariable *GV =
  1878. new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
  1879. ".str");
  1880. GV->setUnnamedAddr(true);
  1881. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  1882. GV->setAlignment(Align.getQuantity());
  1883. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  1884. // String length.
  1885. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  1886. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  1887. // The struct.
  1888. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  1889. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  1890. llvm::GlobalVariable::PrivateLinkage, C,
  1891. "_unnamed_nsstring_");
  1892. // FIXME. Fix section.
  1893. if (const char *Sect =
  1894. LangOpts.ObjCRuntime.isNonFragile()
  1895. ? getContext().getTargetInfo().getNSStringNonFragileABISection()
  1896. : getContext().getTargetInfo().getNSStringSection())
  1897. GV->setSection(Sect);
  1898. Entry.setValue(GV);
  1899. return GV;
  1900. }
  1901. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  1902. if (ObjCFastEnumerationStateType.isNull()) {
  1903. RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
  1904. Context.getTranslationUnitDecl(),
  1905. &Context.Idents.get("__objcFastEnumerationState"));
  1906. D->startDefinition();
  1907. QualType FieldTypes[] = {
  1908. Context.UnsignedLongTy,
  1909. Context.getPointerType(Context.getObjCIdType()),
  1910. Context.getPointerType(Context.UnsignedLongTy),
  1911. Context.getConstantArrayType(Context.UnsignedLongTy,
  1912. llvm::APInt(32, 5), ArrayType::Normal, 0)
  1913. };
  1914. for (size_t i = 0; i < 4; ++i) {
  1915. FieldDecl *Field = FieldDecl::Create(Context,
  1916. D,
  1917. SourceLocation(),
  1918. SourceLocation(), 0,
  1919. FieldTypes[i], /*TInfo=*/0,
  1920. /*BitWidth=*/0,
  1921. /*Mutable=*/false,
  1922. ICIS_NoInit);
  1923. Field->setAccess(AS_public);
  1924. D->addDecl(Field);
  1925. }
  1926. D->completeDefinition();
  1927. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  1928. }
  1929. return ObjCFastEnumerationStateType;
  1930. }
  1931. llvm::Constant *
  1932. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  1933. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  1934. // Don't emit it as the address of the string, emit the string data itself
  1935. // as an inline array.
  1936. if (E->getCharByteWidth() == 1) {
  1937. SmallString<64> Str(E->getString());
  1938. // Resize the string to the right size, which is indicated by its type.
  1939. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  1940. Str.resize(CAT->getSize().getZExtValue());
  1941. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  1942. }
  1943. llvm::ArrayType *AType =
  1944. cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  1945. llvm::Type *ElemTy = AType->getElementType();
  1946. unsigned NumElements = AType->getNumElements();
  1947. // Wide strings have either 2-byte or 4-byte elements.
  1948. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  1949. SmallVector<uint16_t, 32> Elements;
  1950. Elements.reserve(NumElements);
  1951. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  1952. Elements.push_back(E->getCodeUnit(i));
  1953. Elements.resize(NumElements);
  1954. return llvm::ConstantDataArray::get(VMContext, Elements);
  1955. }
  1956. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  1957. SmallVector<uint32_t, 32> Elements;
  1958. Elements.reserve(NumElements);
  1959. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  1960. Elements.push_back(E->getCodeUnit(i));
  1961. Elements.resize(NumElements);
  1962. return llvm::ConstantDataArray::get(VMContext, Elements);
  1963. }
  1964. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  1965. /// constant array for the given string literal.
  1966. llvm::Constant *
  1967. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  1968. CharUnits Align = getContext().getTypeAlignInChars(S->getType());
  1969. if (S->isAscii() || S->isUTF8()) {
  1970. SmallString<64> Str(S->getString());
  1971. // Resize the string to the right size, which is indicated by its type.
  1972. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
  1973. Str.resize(CAT->getSize().getZExtValue());
  1974. return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
  1975. }
  1976. // FIXME: the following does not memoize wide strings.
  1977. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  1978. llvm::GlobalVariable *GV =
  1979. new llvm::GlobalVariable(getModule(),C->getType(),
  1980. !LangOpts.WritableStrings,
  1981. llvm::GlobalValue::PrivateLinkage,
  1982. C,".str");
  1983. GV->setAlignment(Align.getQuantity());
  1984. GV->setUnnamedAddr(true);
  1985. return GV;
  1986. }
  1987. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  1988. /// array for the given ObjCEncodeExpr node.
  1989. llvm::Constant *
  1990. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  1991. std::string Str;
  1992. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  1993. return GetAddrOfConstantCString(Str);
  1994. }
  1995. /// GenerateWritableString -- Creates storage for a string literal.
  1996. static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
  1997. bool constant,
  1998. CodeGenModule &CGM,
  1999. const char *GlobalName,
  2000. unsigned Alignment) {
  2001. // Create Constant for this string literal. Don't add a '\0'.
  2002. llvm::Constant *C =
  2003. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
  2004. // Create a global variable for this string
  2005. llvm::GlobalVariable *GV =
  2006. new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
  2007. llvm::GlobalValue::PrivateLinkage,
  2008. C, GlobalName);
  2009. GV->setAlignment(Alignment);
  2010. GV->setUnnamedAddr(true);
  2011. return GV;
  2012. }
  2013. /// GetAddrOfConstantString - Returns a pointer to a character array
  2014. /// containing the literal. This contents are exactly that of the
  2015. /// given string, i.e. it will not be null terminated automatically;
  2016. /// see GetAddrOfConstantCString. Note that whether the result is
  2017. /// actually a pointer to an LLVM constant depends on
  2018. /// Feature.WriteableStrings.
  2019. ///
  2020. /// The result has pointer to array type.
  2021. llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
  2022. const char *GlobalName,
  2023. unsigned Alignment) {
  2024. // Get the default prefix if a name wasn't specified.
  2025. if (!GlobalName)
  2026. GlobalName = ".str";
  2027. // Don't share any string literals if strings aren't constant.
  2028. if (LangOpts.WritableStrings)
  2029. return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
  2030. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2031. ConstantStringMap.GetOrCreateValue(Str);
  2032. if (llvm::GlobalVariable *GV = Entry.getValue()) {
  2033. if (Alignment > GV->getAlignment()) {
  2034. GV->setAlignment(Alignment);
  2035. }
  2036. return GV;
  2037. }
  2038. // Create a global variable for this.
  2039. llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
  2040. Alignment);
  2041. Entry.setValue(GV);
  2042. return GV;
  2043. }
  2044. /// GetAddrOfConstantCString - Returns a pointer to a character
  2045. /// array containing the literal and a terminating '\0'
  2046. /// character. The result has pointer to array type.
  2047. llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
  2048. const char *GlobalName,
  2049. unsigned Alignment) {
  2050. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2051. return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
  2052. }
  2053. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2054. /// properties for an implementation.
  2055. void CodeGenModule::EmitObjCPropertyImplementations(const
  2056. ObjCImplementationDecl *D) {
  2057. for (ObjCImplementationDecl::propimpl_iterator
  2058. i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
  2059. ObjCPropertyImplDecl *PID = *i;
  2060. // Dynamic is just for type-checking.
  2061. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2062. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2063. // Determine which methods need to be implemented, some may have
  2064. // been overridden. Note that ::isSynthesized is not the method
  2065. // we want, that just indicates if the decl came from a
  2066. // property. What we want to know is if the method is defined in
  2067. // this implementation.
  2068. if (!D->getInstanceMethod(PD->getGetterName()))
  2069. CodeGenFunction(*this).GenerateObjCGetter(
  2070. const_cast<ObjCImplementationDecl *>(D), PID);
  2071. if (!PD->isReadOnly() &&
  2072. !D->getInstanceMethod(PD->getSetterName()))
  2073. CodeGenFunction(*this).GenerateObjCSetter(
  2074. const_cast<ObjCImplementationDecl *>(D), PID);
  2075. }
  2076. }
  2077. }
  2078. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2079. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2080. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2081. ivar; ivar = ivar->getNextIvar())
  2082. if (ivar->getType().isDestructedType())
  2083. return true;
  2084. return false;
  2085. }
  2086. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2087. /// for an implementation.
  2088. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2089. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2090. if (needsDestructMethod(D)) {
  2091. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2092. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2093. ObjCMethodDecl *DTORMethod =
  2094. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2095. cxxSelector, getContext().VoidTy, 0, D,
  2096. /*isInstance=*/true, /*isVariadic=*/false,
  2097. /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
  2098. /*isDefined=*/false, ObjCMethodDecl::Required);
  2099. D->addInstanceMethod(DTORMethod);
  2100. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2101. D->setHasCXXStructors(true);
  2102. }
  2103. // If the implementation doesn't have any ivar initializers, we don't need
  2104. // a .cxx_construct.
  2105. if (D->getNumIvarInitializers() == 0)
  2106. return;
  2107. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2108. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2109. // The constructor returns 'self'.
  2110. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2111. D->getLocation(),
  2112. D->getLocation(),
  2113. cxxSelector,
  2114. getContext().getObjCIdType(), 0,
  2115. D, /*isInstance=*/true,
  2116. /*isVariadic=*/false,
  2117. /*isSynthesized=*/true,
  2118. /*isImplicitlyDeclared=*/true,
  2119. /*isDefined=*/false,
  2120. ObjCMethodDecl::Required);
  2121. D->addInstanceMethod(CTORMethod);
  2122. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2123. D->setHasCXXStructors(true);
  2124. }
  2125. /// EmitNamespace - Emit all declarations in a namespace.
  2126. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2127. for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
  2128. I != E; ++I)
  2129. EmitTopLevelDecl(*I);
  2130. }
  2131. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2132. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2133. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2134. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2135. ErrorUnsupported(LSD, "linkage spec");
  2136. return;
  2137. }
  2138. for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
  2139. I != E; ++I)
  2140. EmitTopLevelDecl(*I);
  2141. }
  2142. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2143. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2144. // If an error has occurred, stop code generation, but continue
  2145. // parsing and semantic analysis (to ensure all warnings and errors
  2146. // are emitted).
  2147. if (Diags.hasErrorOccurred())
  2148. return;
  2149. // Ignore dependent declarations.
  2150. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2151. return;
  2152. switch (D->getKind()) {
  2153. case Decl::CXXConversion:
  2154. case Decl::CXXMethod:
  2155. case Decl::Function:
  2156. // Skip function templates
  2157. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2158. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2159. return;
  2160. EmitGlobal(cast<FunctionDecl>(D));
  2161. break;
  2162. case Decl::Var:
  2163. EmitGlobal(cast<VarDecl>(D));
  2164. break;
  2165. // Indirect fields from global anonymous structs and unions can be
  2166. // ignored; only the actual variable requires IR gen support.
  2167. case Decl::IndirectField:
  2168. break;
  2169. // C++ Decls
  2170. case Decl::Namespace:
  2171. EmitNamespace(cast<NamespaceDecl>(D));
  2172. break;
  2173. // No code generation needed.
  2174. case Decl::UsingShadow:
  2175. case Decl::Using:
  2176. case Decl::UsingDirective:
  2177. case Decl::ClassTemplate:
  2178. case Decl::FunctionTemplate:
  2179. case Decl::TypeAliasTemplate:
  2180. case Decl::NamespaceAlias:
  2181. case Decl::Block:
  2182. case Decl::Import:
  2183. break;
  2184. case Decl::CXXConstructor:
  2185. // Skip function templates
  2186. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2187. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2188. return;
  2189. EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2190. break;
  2191. case Decl::CXXDestructor:
  2192. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2193. return;
  2194. EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2195. break;
  2196. case Decl::StaticAssert:
  2197. // Nothing to do.
  2198. break;
  2199. // Objective-C Decls
  2200. // Forward declarations, no (immediate) code generation.
  2201. case Decl::ObjCInterface:
  2202. case Decl::ObjCCategory:
  2203. break;
  2204. case Decl::ObjCProtocol: {
  2205. ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
  2206. if (Proto->isThisDeclarationADefinition())
  2207. ObjCRuntime->GenerateProtocol(Proto);
  2208. break;
  2209. }
  2210. case Decl::ObjCCategoryImpl:
  2211. // Categories have properties but don't support synthesize so we
  2212. // can ignore them here.
  2213. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2214. break;
  2215. case Decl::ObjCImplementation: {
  2216. ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
  2217. EmitObjCPropertyImplementations(OMD);
  2218. EmitObjCIvarInitializations(OMD);
  2219. ObjCRuntime->GenerateClass(OMD);
  2220. // Emit global variable debug information.
  2221. if (CGDebugInfo *DI = getModuleDebugInfo())
  2222. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
  2223. OMD->getLocation());
  2224. break;
  2225. }
  2226. case Decl::ObjCMethod: {
  2227. ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
  2228. // If this is not a prototype, emit the body.
  2229. if (OMD->getBody())
  2230. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2231. break;
  2232. }
  2233. case Decl::ObjCCompatibleAlias:
  2234. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2235. break;
  2236. case Decl::LinkageSpec:
  2237. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2238. break;
  2239. case Decl::FileScopeAsm: {
  2240. FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
  2241. StringRef AsmString = AD->getAsmString()->getString();
  2242. const std::string &S = getModule().getModuleInlineAsm();
  2243. if (S.empty())
  2244. getModule().setModuleInlineAsm(AsmString);
  2245. else if (S.end()[-1] == '\n')
  2246. getModule().setModuleInlineAsm(S + AsmString.str());
  2247. else
  2248. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2249. break;
  2250. }
  2251. default:
  2252. // Make sure we handled everything we should, every other kind is a
  2253. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2254. // function. Need to recode Decl::Kind to do that easily.
  2255. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2256. }
  2257. }
  2258. /// Turns the given pointer into a constant.
  2259. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2260. const void *Ptr) {
  2261. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2262. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2263. return llvm::ConstantInt::get(i64, PtrInt);
  2264. }
  2265. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2266. llvm::NamedMDNode *&GlobalMetadata,
  2267. GlobalDecl D,
  2268. llvm::GlobalValue *Addr) {
  2269. if (!GlobalMetadata)
  2270. GlobalMetadata =
  2271. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2272. // TODO: should we report variant information for ctors/dtors?
  2273. llvm::Value *Ops[] = {
  2274. Addr,
  2275. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2276. };
  2277. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2278. }
  2279. /// Emits metadata nodes associating all the global values in the
  2280. /// current module with the Decls they came from. This is useful for
  2281. /// projects using IR gen as a subroutine.
  2282. ///
  2283. /// Since there's currently no way to associate an MDNode directly
  2284. /// with an llvm::GlobalValue, we create a global named metadata
  2285. /// with the name 'clang.global.decl.ptrs'.
  2286. void CodeGenModule::EmitDeclMetadata() {
  2287. llvm::NamedMDNode *GlobalMetadata = 0;
  2288. // StaticLocalDeclMap
  2289. for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
  2290. I = MangledDeclNames.begin(), E = MangledDeclNames.end();
  2291. I != E; ++I) {
  2292. llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
  2293. EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
  2294. }
  2295. }
  2296. /// Emits metadata nodes for all the local variables in the current
  2297. /// function.
  2298. void CodeGenFunction::EmitDeclMetadata() {
  2299. if (LocalDeclMap.empty()) return;
  2300. llvm::LLVMContext &Context = getLLVMContext();
  2301. // Find the unique metadata ID for this name.
  2302. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2303. llvm::NamedMDNode *GlobalMetadata = 0;
  2304. for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
  2305. I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
  2306. const Decl *D = I->first;
  2307. llvm::Value *Addr = I->second;
  2308. if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2309. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2310. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2311. } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2312. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2313. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2314. }
  2315. }
  2316. }
  2317. void CodeGenModule::EmitCoverageFile() {
  2318. if (!getCodeGenOpts().CoverageFile.empty()) {
  2319. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2320. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2321. llvm::LLVMContext &Ctx = TheModule.getContext();
  2322. llvm::MDString *CoverageFile =
  2323. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2324. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2325. llvm::MDNode *CU = CUNode->getOperand(i);
  2326. llvm::Value *node[] = { CoverageFile, CU };
  2327. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2328. GCov->addOperand(N);
  2329. }
  2330. }
  2331. }
  2332. }