CodeGenModule.cpp 105 KB

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