CodeGenModule.cpp 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431
  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 "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CGOpenMPRuntime.h"
  21. #include "CodeGenFunction.h"
  22. #include "CodeGenPGO.h"
  23. #include "CoverageMappingGen.h"
  24. #include "CodeGenTBAA.h"
  25. #include "TargetInfo.h"
  26. #include "clang/AST/ASTContext.h"
  27. #include "clang/AST/CharUnits.h"
  28. #include "clang/AST/DeclCXX.h"
  29. #include "clang/AST/DeclObjC.h"
  30. #include "clang/AST/DeclTemplate.h"
  31. #include "clang/AST/Mangle.h"
  32. #include "clang/AST/RecordLayout.h"
  33. #include "clang/AST/RecursiveASTVisitor.h"
  34. #include "clang/Basic/Builtins.h"
  35. #include "clang/Basic/CharInfo.h"
  36. #include "clang/Basic/Diagnostic.h"
  37. #include "clang/Basic/Module.h"
  38. #include "clang/Basic/SourceManager.h"
  39. #include "clang/Basic/TargetInfo.h"
  40. #include "clang/Basic/Version.h"
  41. #include "clang/Frontend/CodeGenOptions.h"
  42. #include "clang/Sema/SemaDiagnostic.h"
  43. #include "llvm/ADT/APSInt.h"
  44. #include "llvm/ADT/Triple.h"
  45. #include "llvm/IR/CallSite.h"
  46. #include "llvm/IR/CallingConv.h"
  47. #include "llvm/IR/DataLayout.h"
  48. #include "llvm/IR/Intrinsics.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/Module.h"
  51. #include "llvm/ProfileData/InstrProfReader.h"
  52. #include "llvm/Support/ConvertUTF.h"
  53. #include "llvm/Support/ErrorHandling.h"
  54. using namespace clang;
  55. using namespace CodeGen;
  56. static const char AnnotationSection[] = "llvm.metadata";
  57. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  58. switch (CGM.getTarget().getCXXABI().getKind()) {
  59. case TargetCXXABI::GenericAArch64:
  60. case TargetCXXABI::GenericARM:
  61. case TargetCXXABI::iOS:
  62. case TargetCXXABI::iOS64:
  63. case TargetCXXABI::GenericItanium:
  64. return CreateItaniumCXXABI(CGM);
  65. case TargetCXXABI::Microsoft:
  66. return CreateMicrosoftCXXABI(CGM);
  67. }
  68. llvm_unreachable("invalid C++ ABI kind");
  69. }
  70. CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
  71. llvm::Module &M, const llvm::DataLayout &TD,
  72. DiagnosticsEngine &diags,
  73. CoverageSourceInfo *CoverageInfo)
  74. : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
  75. Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
  76. ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
  77. TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
  78. ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
  79. CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
  80. NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
  81. CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
  82. NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
  83. NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
  84. BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
  85. GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
  86. LifetimeEndFn(nullptr), SanitizerBL(llvm::SpecialCaseList::createOrDie(
  87. CGO.SanitizerBlacklistFile)),
  88. SanitizerMD(new SanitizerMetadata(*this)) {
  89. // Initialize the type cache.
  90. llvm::LLVMContext &LLVMContext = M.getContext();
  91. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  92. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  93. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  94. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  95. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  96. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  97. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  98. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  99. PointerAlignInBytes =
  100. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  101. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  102. IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
  103. Int8PtrTy = Int8Ty->getPointerTo(0);
  104. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  105. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  106. if (LangOpts.ObjC1)
  107. createObjCRuntime();
  108. if (LangOpts.OpenCL)
  109. createOpenCLRuntime();
  110. if (LangOpts.OpenMP)
  111. createOpenMPRuntime();
  112. if (LangOpts.CUDA)
  113. createCUDARuntime();
  114. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  115. if (LangOpts.Sanitize.Thread ||
  116. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  117. TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  118. getCXXABI().getMangleContext());
  119. // If debug info or coverage generation is enabled, create the CGDebugInfo
  120. // object.
  121. if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
  122. CodeGenOpts.EmitGcovArcs ||
  123. CodeGenOpts.EmitGcovNotes)
  124. DebugInfo = new CGDebugInfo(*this);
  125. Block.GlobalUniqueCount = 0;
  126. if (C.getLangOpts().ObjCAutoRefCount)
  127. ARCData = new ARCEntrypoints();
  128. RRData = new RREntrypoints();
  129. if (!CodeGenOpts.InstrProfileInput.empty()) {
  130. if (std::error_code EC = llvm::IndexedInstrProfReader::create(
  131. CodeGenOpts.InstrProfileInput, PGOReader)) {
  132. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  133. "Could not read profile: %0");
  134. getDiags().Report(DiagID) << EC.message();
  135. }
  136. }
  137. // If coverage mapping generation is enabled, create the
  138. // CoverageMappingModuleGen object.
  139. if (CodeGenOpts.CoverageMapping)
  140. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  141. }
  142. CodeGenModule::~CodeGenModule() {
  143. delete ObjCRuntime;
  144. delete OpenCLRuntime;
  145. delete OpenMPRuntime;
  146. delete CUDARuntime;
  147. delete TheTargetCodeGenInfo;
  148. delete TBAA;
  149. delete DebugInfo;
  150. delete ARCData;
  151. delete RRData;
  152. }
  153. void CodeGenModule::createObjCRuntime() {
  154. // This is just isGNUFamily(), but we want to force implementors of
  155. // new ABIs to decide how best to do this.
  156. switch (LangOpts.ObjCRuntime.getKind()) {
  157. case ObjCRuntime::GNUstep:
  158. case ObjCRuntime::GCC:
  159. case ObjCRuntime::ObjFW:
  160. ObjCRuntime = CreateGNUObjCRuntime(*this);
  161. return;
  162. case ObjCRuntime::FragileMacOSX:
  163. case ObjCRuntime::MacOSX:
  164. case ObjCRuntime::iOS:
  165. ObjCRuntime = CreateMacObjCRuntime(*this);
  166. return;
  167. }
  168. llvm_unreachable("bad runtime kind");
  169. }
  170. void CodeGenModule::createOpenCLRuntime() {
  171. OpenCLRuntime = new CGOpenCLRuntime(*this);
  172. }
  173. void CodeGenModule::createOpenMPRuntime() {
  174. OpenMPRuntime = new CGOpenMPRuntime(*this);
  175. }
  176. void CodeGenModule::createCUDARuntime() {
  177. CUDARuntime = CreateNVCUDARuntime(*this);
  178. }
  179. void CodeGenModule::applyReplacements() {
  180. for (ReplacementsTy::iterator I = Replacements.begin(),
  181. E = Replacements.end();
  182. I != E; ++I) {
  183. StringRef MangledName = I->first();
  184. llvm::Constant *Replacement = I->second;
  185. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  186. if (!Entry)
  187. continue;
  188. auto *OldF = cast<llvm::Function>(Entry);
  189. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  190. if (!NewF) {
  191. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  192. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  193. } else {
  194. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  195. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  196. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  197. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  198. }
  199. }
  200. // Replace old with new, but keep the old order.
  201. OldF->replaceAllUsesWith(Replacement);
  202. if (NewF) {
  203. NewF->removeFromParent();
  204. OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
  205. }
  206. OldF->eraseFromParent();
  207. }
  208. }
  209. // This is only used in aliases that we created and we know they have a
  210. // linear structure.
  211. static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
  212. llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
  213. const llvm::Constant *C = &GA;
  214. for (;;) {
  215. C = C->stripPointerCasts();
  216. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  217. return GO;
  218. // stripPointerCasts will not walk over weak aliases.
  219. auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
  220. if (!GA2)
  221. return nullptr;
  222. if (!Visited.insert(GA2))
  223. return nullptr;
  224. C = GA2->getAliasee();
  225. }
  226. }
  227. void CodeGenModule::checkAliases() {
  228. // Check if the constructed aliases are well formed. It is really unfortunate
  229. // that we have to do this in CodeGen, but we only construct mangled names
  230. // and aliases during codegen.
  231. bool Error = false;
  232. DiagnosticsEngine &Diags = getDiags();
  233. for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
  234. E = Aliases.end(); I != E; ++I) {
  235. const GlobalDecl &GD = *I;
  236. const auto *D = cast<ValueDecl>(GD.getDecl());
  237. const AliasAttr *AA = D->getAttr<AliasAttr>();
  238. StringRef MangledName = getMangledName(GD);
  239. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  240. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  241. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  242. if (!GV) {
  243. Error = true;
  244. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  245. } else if (GV->isDeclaration()) {
  246. Error = true;
  247. Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
  248. }
  249. llvm::Constant *Aliasee = Alias->getAliasee();
  250. llvm::GlobalValue *AliaseeGV;
  251. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  252. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  253. else
  254. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  255. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  256. StringRef AliasSection = SA->getName();
  257. if (AliasSection != AliaseeGV->getSection())
  258. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  259. << AliasSection;
  260. }
  261. // We have to handle alias to weak aliases in here. LLVM itself disallows
  262. // this since the object semantics would not match the IL one. For
  263. // compatibility with gcc we implement it by just pointing the alias
  264. // to its aliasee's aliasee. We also warn, since the user is probably
  265. // expecting the link to be weak.
  266. if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
  267. if (GA->mayBeOverridden()) {
  268. Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
  269. << GV->getName() << GA->getName();
  270. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  271. GA->getAliasee(), Alias->getType());
  272. Alias->setAliasee(Aliasee);
  273. }
  274. }
  275. }
  276. if (!Error)
  277. return;
  278. for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
  279. E = Aliases.end(); I != E; ++I) {
  280. const GlobalDecl &GD = *I;
  281. StringRef MangledName = getMangledName(GD);
  282. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  283. auto *Alias = cast<llvm::GlobalAlias>(Entry);
  284. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  285. Alias->eraseFromParent();
  286. }
  287. }
  288. void CodeGenModule::clear() {
  289. DeferredDeclsToEmit.clear();
  290. }
  291. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  292. StringRef MainFile) {
  293. if (!hasDiagnostics())
  294. return;
  295. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  296. if (MainFile.empty())
  297. MainFile = "<stdin>";
  298. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  299. } else
  300. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
  301. << Mismatched;
  302. }
  303. void CodeGenModule::Release() {
  304. EmitDeferred();
  305. applyReplacements();
  306. checkAliases();
  307. EmitCXXGlobalInitFunc();
  308. EmitCXXGlobalDtorFunc();
  309. EmitCXXThreadLocalInitFunc();
  310. if (ObjCRuntime)
  311. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  312. AddGlobalCtor(ObjCInitFunction);
  313. if (getCodeGenOpts().ProfileInstrGenerate)
  314. if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
  315. AddGlobalCtor(PGOInit, 0);
  316. if (PGOReader && PGOStats.hasDiagnostics())
  317. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  318. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  319. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  320. EmitGlobalAnnotations();
  321. EmitStaticExternCAliases();
  322. EmitDeferredUnusedCoverageMappings();
  323. if (CoverageMapping)
  324. CoverageMapping->emit();
  325. emitLLVMUsed();
  326. if (CodeGenOpts.Autolink &&
  327. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  328. EmitModuleLinkOptions();
  329. }
  330. if (CodeGenOpts.DwarfVersion)
  331. // We actually want the latest version when there are conflicts.
  332. // We can change from Warning to Latest if such mode is supported.
  333. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  334. CodeGenOpts.DwarfVersion);
  335. if (DebugInfo)
  336. // We support a single version in the linked module. The LLVM
  337. // parser will drop debug info with a different version number
  338. // (and warn about it, too).
  339. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  340. llvm::DEBUG_METADATA_VERSION);
  341. // We need to record the widths of enums and wchar_t, so that we can generate
  342. // the correct build attributes in the ARM backend.
  343. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  344. if ( Arch == llvm::Triple::arm
  345. || Arch == llvm::Triple::armeb
  346. || Arch == llvm::Triple::thumb
  347. || Arch == llvm::Triple::thumbeb) {
  348. // Width of wchar_t in bytes
  349. uint64_t WCharWidth =
  350. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  351. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  352. // The minimum width of an enum in bytes
  353. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  354. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  355. }
  356. SimplifyPersonality();
  357. if (getCodeGenOpts().EmitDeclMetadata)
  358. EmitDeclMetadata();
  359. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  360. EmitCoverageFile();
  361. if (DebugInfo)
  362. DebugInfo->finalize();
  363. EmitVersionIdentMetadata();
  364. EmitTargetMetadata();
  365. }
  366. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  367. // Make sure that this type is translated.
  368. Types.UpdateCompletedType(TD);
  369. }
  370. llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
  371. if (!TBAA)
  372. return nullptr;
  373. return TBAA->getTBAAInfo(QTy);
  374. }
  375. llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
  376. if (!TBAA)
  377. return nullptr;
  378. return TBAA->getTBAAInfoForVTablePtr();
  379. }
  380. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  381. if (!TBAA)
  382. return nullptr;
  383. return TBAA->getTBAAStructInfo(QTy);
  384. }
  385. llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
  386. if (!TBAA)
  387. return nullptr;
  388. return TBAA->getTBAAStructTypeInfo(QTy);
  389. }
  390. llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
  391. llvm::MDNode *AccessN,
  392. uint64_t O) {
  393. if (!TBAA)
  394. return nullptr;
  395. return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
  396. }
  397. /// Decorate the instruction with a TBAA tag. For both scalar TBAA
  398. /// and struct-path aware TBAA, the tag has the same format:
  399. /// base type, access type and offset.
  400. /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
  401. void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
  402. llvm::MDNode *TBAAInfo,
  403. bool ConvertTypeToTag) {
  404. if (ConvertTypeToTag && TBAA)
  405. Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
  406. TBAA->getTBAAScalarTagInfo(TBAAInfo));
  407. else
  408. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
  409. }
  410. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  411. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  412. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  413. }
  414. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  415. /// specified stmt yet.
  416. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  417. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  418. "cannot compile this %0 yet");
  419. std::string Msg = Type;
  420. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  421. << Msg << S->getSourceRange();
  422. }
  423. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  424. /// specified decl yet.
  425. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  426. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  427. "cannot compile this %0 yet");
  428. std::string Msg = Type;
  429. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  430. }
  431. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  432. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  433. }
  434. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  435. const NamedDecl *D) const {
  436. // Internal definitions always have default visibility.
  437. if (GV->hasLocalLinkage()) {
  438. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  439. return;
  440. }
  441. // Set visibility for definitions.
  442. LinkageInfo LV = D->getLinkageAndVisibility();
  443. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  444. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  445. }
  446. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  447. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  448. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  449. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  450. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  451. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  452. }
  453. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  454. CodeGenOptions::TLSModel M) {
  455. switch (M) {
  456. case CodeGenOptions::GeneralDynamicTLSModel:
  457. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  458. case CodeGenOptions::LocalDynamicTLSModel:
  459. return llvm::GlobalVariable::LocalDynamicTLSModel;
  460. case CodeGenOptions::InitialExecTLSModel:
  461. return llvm::GlobalVariable::InitialExecTLSModel;
  462. case CodeGenOptions::LocalExecTLSModel:
  463. return llvm::GlobalVariable::LocalExecTLSModel;
  464. }
  465. llvm_unreachable("Invalid TLS model!");
  466. }
  467. void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
  468. const VarDecl &D) const {
  469. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  470. llvm::GlobalVariable::ThreadLocalMode TLM;
  471. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  472. // Override the TLS model if it is explicitly specified.
  473. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  474. TLM = GetLLVMTLSModel(Attr->getModel());
  475. }
  476. GV->setThreadLocalMode(TLM);
  477. }
  478. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  479. StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
  480. if (!FoundStr.empty())
  481. return FoundStr;
  482. const auto *ND = cast<NamedDecl>(GD.getDecl());
  483. SmallString<256> Buffer;
  484. StringRef Str;
  485. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  486. llvm::raw_svector_ostream Out(Buffer);
  487. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  488. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  489. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  490. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  491. else
  492. getCXXABI().getMangleContext().mangleName(ND, Out);
  493. Str = Out.str();
  494. } else {
  495. IdentifierInfo *II = ND->getIdentifier();
  496. assert(II && "Attempt to mangle unnamed decl.");
  497. Str = II->getName();
  498. }
  499. // Keep the first result in the case of a mangling collision.
  500. auto Result = Manglings.insert(std::make_pair(Str, GD));
  501. return FoundStr = Result.first->first();
  502. }
  503. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  504. const BlockDecl *BD) {
  505. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  506. const Decl *D = GD.getDecl();
  507. SmallString<256> Buffer;
  508. llvm::raw_svector_ostream Out(Buffer);
  509. if (!D)
  510. MangleCtx.mangleGlobalBlock(BD,
  511. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  512. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  513. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  514. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  515. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  516. else
  517. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  518. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  519. return Result.first->first();
  520. }
  521. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  522. return getModule().getNamedValue(Name);
  523. }
  524. /// AddGlobalCtor - Add a function to the list that will be called before
  525. /// main() runs.
  526. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  527. llvm::Constant *AssociatedData) {
  528. // FIXME: Type coercion of void()* types.
  529. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  530. }
  531. /// AddGlobalDtor - Add a function to the list that will be called
  532. /// when the module is unloaded.
  533. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  534. // FIXME: Type coercion of void()* types.
  535. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  536. }
  537. void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
  538. // Ctor function type is void()*.
  539. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  540. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  541. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  542. llvm::StructType *CtorStructTy = llvm::StructType::get(
  543. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, NULL);
  544. // Construct the constructor and destructor arrays.
  545. SmallVector<llvm::Constant*, 8> Ctors;
  546. for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
  547. llvm::Constant *S[] = {
  548. llvm::ConstantInt::get(Int32Ty, I->Priority, false),
  549. llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
  550. (I->AssociatedData
  551. ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
  552. : llvm::Constant::getNullValue(VoidPtrTy))
  553. };
  554. Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
  555. }
  556. if (!Ctors.empty()) {
  557. llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
  558. new llvm::GlobalVariable(TheModule, AT, false,
  559. llvm::GlobalValue::AppendingLinkage,
  560. llvm::ConstantArray::get(AT, Ctors),
  561. GlobalName);
  562. }
  563. }
  564. llvm::GlobalValue::LinkageTypes
  565. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  566. const auto *D = cast<FunctionDecl>(GD.getDecl());
  567. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  568. if (isa<CXXDestructorDecl>(D) &&
  569. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  570. GD.getDtorType())) {
  571. // Destructor variants in the Microsoft C++ ABI are always internal or
  572. // linkonce_odr thunks emitted on an as-needed basis.
  573. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  574. : llvm::GlobalValue::LinkOnceODRLinkage;
  575. }
  576. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  577. }
  578. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  579. llvm::Function *F) {
  580. setNonAliasAttributes(D, F);
  581. }
  582. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  583. const CGFunctionInfo &Info,
  584. llvm::Function *F) {
  585. unsigned CallingConv;
  586. AttributeListType AttributeList;
  587. ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
  588. F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
  589. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  590. }
  591. /// Determines whether the language options require us to model
  592. /// unwind exceptions. We treat -fexceptions as mandating this
  593. /// except under the fragile ObjC ABI with only ObjC exceptions
  594. /// enabled. This means, for example, that C with -fexceptions
  595. /// enables this.
  596. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  597. // If exceptions are completely disabled, obviously this is false.
  598. if (!LangOpts.Exceptions) return false;
  599. // If C++ exceptions are enabled, this is true.
  600. if (LangOpts.CXXExceptions) return true;
  601. // If ObjC exceptions are enabled, this depends on the ABI.
  602. if (LangOpts.ObjCExceptions) {
  603. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  604. }
  605. return true;
  606. }
  607. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  608. llvm::Function *F) {
  609. llvm::AttrBuilder B;
  610. if (CodeGenOpts.UnwindTables)
  611. B.addAttribute(llvm::Attribute::UWTable);
  612. if (!hasUnwindExceptions(LangOpts))
  613. B.addAttribute(llvm::Attribute::NoUnwind);
  614. if (D->hasAttr<NakedAttr>()) {
  615. // Naked implies noinline: we should not be inlining such functions.
  616. B.addAttribute(llvm::Attribute::Naked);
  617. B.addAttribute(llvm::Attribute::NoInline);
  618. } else if (D->hasAttr<OptimizeNoneAttr>()) {
  619. // OptimizeNone implies noinline; we should not be inlining such functions.
  620. B.addAttribute(llvm::Attribute::OptimizeNone);
  621. B.addAttribute(llvm::Attribute::NoInline);
  622. } else if (D->hasAttr<NoDuplicateAttr>()) {
  623. B.addAttribute(llvm::Attribute::NoDuplicate);
  624. } else if (D->hasAttr<NoInlineAttr>()) {
  625. B.addAttribute(llvm::Attribute::NoInline);
  626. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  627. !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
  628. llvm::Attribute::NoInline)) {
  629. // (noinline wins over always_inline, and we can't specify both in IR)
  630. B.addAttribute(llvm::Attribute::AlwaysInline);
  631. }
  632. if (D->hasAttr<ColdAttr>()) {
  633. B.addAttribute(llvm::Attribute::OptimizeForSize);
  634. B.addAttribute(llvm::Attribute::Cold);
  635. }
  636. if (D->hasAttr<MinSizeAttr>())
  637. B.addAttribute(llvm::Attribute::MinSize);
  638. if (D->hasAttr<OptimizeNoneAttr>()) {
  639. // OptimizeNone wins over OptimizeForSize and MinSize.
  640. B.removeAttribute(llvm::Attribute::OptimizeForSize);
  641. B.removeAttribute(llvm::Attribute::MinSize);
  642. }
  643. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  644. B.addAttribute(llvm::Attribute::StackProtect);
  645. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  646. B.addAttribute(llvm::Attribute::StackProtectStrong);
  647. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  648. B.addAttribute(llvm::Attribute::StackProtectReq);
  649. // Add sanitizer attributes if function is not blacklisted.
  650. if (!SanitizerBL.isIn(*F)) {
  651. // When AddressSanitizer is enabled, set SanitizeAddress attribute
  652. // unless __attribute__((no_sanitize_address)) is used.
  653. if (LangOpts.Sanitize.Address && !D->hasAttr<NoSanitizeAddressAttr>())
  654. B.addAttribute(llvm::Attribute::SanitizeAddress);
  655. // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
  656. if (LangOpts.Sanitize.Thread && !D->hasAttr<NoSanitizeThreadAttr>())
  657. B.addAttribute(llvm::Attribute::SanitizeThread);
  658. // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
  659. if (LangOpts.Sanitize.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
  660. B.addAttribute(llvm::Attribute::SanitizeMemory);
  661. }
  662. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  663. llvm::AttributeSet::get(
  664. F->getContext(), llvm::AttributeSet::FunctionIndex, B));
  665. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  666. F->setUnnamedAddr(true);
  667. else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
  668. if (MD->isVirtual())
  669. F->setUnnamedAddr(true);
  670. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  671. if (alignment)
  672. F->setAlignment(alignment);
  673. // C++ ABI requires 2-byte alignment for member functions.
  674. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  675. F->setAlignment(2);
  676. }
  677. void CodeGenModule::SetCommonAttributes(const Decl *D,
  678. llvm::GlobalValue *GV) {
  679. if (const auto *ND = dyn_cast<NamedDecl>(D))
  680. setGlobalVisibility(GV, ND);
  681. else
  682. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  683. if (D->hasAttr<UsedAttr>())
  684. addUsedGlobal(GV);
  685. }
  686. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  687. llvm::GlobalObject *GO) {
  688. SetCommonAttributes(D, GO);
  689. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  690. GO->setSection(SA->getName());
  691. getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
  692. }
  693. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  694. llvm::Function *F,
  695. const CGFunctionInfo &FI) {
  696. SetLLVMFunctionAttributes(D, FI, F);
  697. SetLLVMFunctionAttributesForDefinition(D, F);
  698. F->setLinkage(llvm::Function::InternalLinkage);
  699. setNonAliasAttributes(D, F);
  700. }
  701. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  702. const NamedDecl *ND) {
  703. // Set linkage and visibility in case we never see a definition.
  704. LinkageInfo LV = ND->getLinkageAndVisibility();
  705. if (LV.getLinkage() != ExternalLinkage) {
  706. // Don't set internal linkage on declarations.
  707. } else {
  708. if (ND->hasAttr<DLLImportAttr>()) {
  709. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  710. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  711. } else if (ND->hasAttr<DLLExportAttr>()) {
  712. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  713. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  714. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  715. // "extern_weak" is overloaded in LLVM; we probably should have
  716. // separate linkage types for this.
  717. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  718. }
  719. // Set visibility on a declaration only if it's explicit.
  720. if (LV.isVisibilityExplicit())
  721. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  722. }
  723. }
  724. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
  725. llvm::Function *F,
  726. bool IsIncompleteFunction) {
  727. if (unsigned IID = F->getIntrinsicID()) {
  728. // If this is an intrinsic function, set the function's attributes
  729. // to the intrinsic's attributes.
  730. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
  731. (llvm::Intrinsic::ID)IID));
  732. return;
  733. }
  734. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  735. if (!IsIncompleteFunction)
  736. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  737. // Add the Returned attribute for "this", except for iOS 5 and earlier
  738. // where substantial code, including the libstdc++ dylib, was compiled with
  739. // GCC and does not actually return "this".
  740. if (getCXXABI().HasThisReturn(GD) &&
  741. !(getTarget().getTriple().isiOS() &&
  742. getTarget().getTriple().isOSVersionLT(6))) {
  743. assert(!F->arg_empty() &&
  744. F->arg_begin()->getType()
  745. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  746. "unexpected this return");
  747. F->addAttribute(1, llvm::Attribute::Returned);
  748. }
  749. // Only a few attributes are set on declarations; these may later be
  750. // overridden by a definition.
  751. setLinkageAndVisibilityForGV(F, FD);
  752. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  753. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  754. // Don't dllexport/import destructor thunks.
  755. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  756. }
  757. }
  758. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  759. F->setSection(SA->getName());
  760. // A replaceable global allocation function does not act like a builtin by
  761. // default, only if it is invoked by a new-expression or delete-expression.
  762. if (FD->isReplaceableGlobalAllocationFunction())
  763. F->addAttribute(llvm::AttributeSet::FunctionIndex,
  764. llvm::Attribute::NoBuiltin);
  765. }
  766. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  767. assert(!GV->isDeclaration() &&
  768. "Only globals with definition can force usage.");
  769. LLVMUsed.push_back(GV);
  770. }
  771. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  772. assert(!GV->isDeclaration() &&
  773. "Only globals with definition can force usage.");
  774. LLVMCompilerUsed.push_back(GV);
  775. }
  776. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  777. std::vector<llvm::WeakVH> &List) {
  778. // Don't create llvm.used if there is no need.
  779. if (List.empty())
  780. return;
  781. // Convert List to what ConstantArray needs.
  782. SmallVector<llvm::Constant*, 8> UsedArray;
  783. UsedArray.resize(List.size());
  784. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  785. UsedArray[i] =
  786. llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
  787. CGM.Int8PtrTy);
  788. }
  789. if (UsedArray.empty())
  790. return;
  791. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  792. auto *GV = new llvm::GlobalVariable(
  793. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  794. llvm::ConstantArray::get(ATy, UsedArray), Name);
  795. GV->setSection("llvm.metadata");
  796. }
  797. void CodeGenModule::emitLLVMUsed() {
  798. emitUsed(*this, "llvm.used", LLVMUsed);
  799. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  800. }
  801. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  802. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  803. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  804. }
  805. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  806. llvm::SmallString<32> Opt;
  807. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  808. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  809. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  810. }
  811. void CodeGenModule::AddDependentLib(StringRef Lib) {
  812. llvm::SmallString<24> Opt;
  813. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  814. llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  815. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  816. }
  817. /// \brief Add link options implied by the given module, including modules
  818. /// it depends on, using a postorder walk.
  819. static void addLinkOptionsPostorder(CodeGenModule &CGM,
  820. Module *Mod,
  821. SmallVectorImpl<llvm::Value *> &Metadata,
  822. llvm::SmallPtrSet<Module *, 16> &Visited) {
  823. // Import this module's parent.
  824. if (Mod->Parent && Visited.insert(Mod->Parent)) {
  825. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  826. }
  827. // Import this module's dependencies.
  828. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  829. if (Visited.insert(Mod->Imports[I-1]))
  830. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  831. }
  832. // Add linker options to link against the libraries/frameworks
  833. // described by this module.
  834. llvm::LLVMContext &Context = CGM.getLLVMContext();
  835. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  836. // Link against a framework. Frameworks are currently Darwin only, so we
  837. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  838. if (Mod->LinkLibraries[I-1].IsFramework) {
  839. llvm::Value *Args[2] = {
  840. llvm::MDString::get(Context, "-framework"),
  841. llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
  842. };
  843. Metadata.push_back(llvm::MDNode::get(Context, Args));
  844. continue;
  845. }
  846. // Link against a library.
  847. llvm::SmallString<24> Opt;
  848. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  849. Mod->LinkLibraries[I-1].Library, Opt);
  850. llvm::Value *OptString = llvm::MDString::get(Context, Opt);
  851. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  852. }
  853. }
  854. void CodeGenModule::EmitModuleLinkOptions() {
  855. // Collect the set of all of the modules we want to visit to emit link
  856. // options, which is essentially the imported modules and all of their
  857. // non-explicit child modules.
  858. llvm::SetVector<clang::Module *> LinkModules;
  859. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  860. SmallVector<clang::Module *, 16> Stack;
  861. // Seed the stack with imported modules.
  862. for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
  863. MEnd = ImportedModules.end();
  864. M != MEnd; ++M) {
  865. if (Visited.insert(*M))
  866. Stack.push_back(*M);
  867. }
  868. // Find all of the modules to import, making a little effort to prune
  869. // non-leaf modules.
  870. while (!Stack.empty()) {
  871. clang::Module *Mod = Stack.pop_back_val();
  872. bool AnyChildren = false;
  873. // Visit the submodules of this module.
  874. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  875. SubEnd = Mod->submodule_end();
  876. Sub != SubEnd; ++Sub) {
  877. // Skip explicit children; they need to be explicitly imported to be
  878. // linked against.
  879. if ((*Sub)->IsExplicit)
  880. continue;
  881. if (Visited.insert(*Sub)) {
  882. Stack.push_back(*Sub);
  883. AnyChildren = true;
  884. }
  885. }
  886. // We didn't find any children, so add this module to the list of
  887. // modules to link against.
  888. if (!AnyChildren) {
  889. LinkModules.insert(Mod);
  890. }
  891. }
  892. // Add link options for all of the imported modules in reverse topological
  893. // order. We don't do anything to try to order import link flags with respect
  894. // to linker options inserted by things like #pragma comment().
  895. SmallVector<llvm::Value *, 16> MetadataArgs;
  896. Visited.clear();
  897. for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
  898. MEnd = LinkModules.end();
  899. M != MEnd; ++M) {
  900. if (Visited.insert(*M))
  901. addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
  902. }
  903. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  904. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  905. // Add the linker options metadata flag.
  906. getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
  907. llvm::MDNode::get(getLLVMContext(),
  908. LinkerOptionsMetadata));
  909. }
  910. void CodeGenModule::EmitDeferred() {
  911. // Emit code for any potentially referenced deferred decls. Since a
  912. // previously unused static decl may become used during the generation of code
  913. // for a static function, iterate until no changes are made.
  914. while (true) {
  915. if (!DeferredVTables.empty()) {
  916. EmitDeferredVTables();
  917. // Emitting a v-table doesn't directly cause more v-tables to
  918. // become deferred, although it can cause functions to be
  919. // emitted that then need those v-tables.
  920. assert(DeferredVTables.empty());
  921. }
  922. // Stop if we're out of both deferred v-tables and deferred declarations.
  923. if (DeferredDeclsToEmit.empty()) break;
  924. DeferredGlobal &G = DeferredDeclsToEmit.back();
  925. GlobalDecl D = G.GD;
  926. llvm::GlobalValue *GV = G.GV;
  927. DeferredDeclsToEmit.pop_back();
  928. assert(GV == GetGlobalValue(getMangledName(D)));
  929. // Check to see if we've already emitted this. This is necessary
  930. // for a couple of reasons: first, decls can end up in the
  931. // deferred-decls queue multiple times, and second, decls can end
  932. // up with definitions in unusual ways (e.g. by an extern inline
  933. // function acquiring a strong function redefinition). Just
  934. // ignore these cases.
  935. if(!GV->isDeclaration())
  936. continue;
  937. // Otherwise, emit the definition and move on to the next one.
  938. EmitGlobalDefinition(D, GV);
  939. }
  940. }
  941. void CodeGenModule::EmitGlobalAnnotations() {
  942. if (Annotations.empty())
  943. return;
  944. // Create a new global variable for the ConstantStruct in the Module.
  945. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  946. Annotations[0]->getType(), Annotations.size()), Annotations);
  947. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  948. llvm::GlobalValue::AppendingLinkage,
  949. Array, "llvm.global.annotations");
  950. gv->setSection(AnnotationSection);
  951. }
  952. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  953. llvm::Constant *&AStr = AnnotationStrings[Str];
  954. if (AStr)
  955. return AStr;
  956. // Not found yet, create a new global.
  957. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  958. auto *gv =
  959. new llvm::GlobalVariable(getModule(), s->getType(), true,
  960. llvm::GlobalValue::PrivateLinkage, s, ".str");
  961. gv->setSection(AnnotationSection);
  962. gv->setUnnamedAddr(true);
  963. AStr = gv;
  964. return gv;
  965. }
  966. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  967. SourceManager &SM = getContext().getSourceManager();
  968. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  969. if (PLoc.isValid())
  970. return EmitAnnotationString(PLoc.getFilename());
  971. return EmitAnnotationString(SM.getBufferName(Loc));
  972. }
  973. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  974. SourceManager &SM = getContext().getSourceManager();
  975. PresumedLoc PLoc = SM.getPresumedLoc(L);
  976. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  977. SM.getExpansionLineNumber(L);
  978. return llvm::ConstantInt::get(Int32Ty, LineNo);
  979. }
  980. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  981. const AnnotateAttr *AA,
  982. SourceLocation L) {
  983. // Get the globals for file name, annotation, and the line number.
  984. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  985. *UnitGV = EmitAnnotationUnit(L),
  986. *LineNoCst = EmitAnnotationLineNo(L);
  987. // Create the ConstantStruct for the global annotation.
  988. llvm::Constant *Fields[4] = {
  989. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  990. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  991. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  992. LineNoCst
  993. };
  994. return llvm::ConstantStruct::getAnon(Fields);
  995. }
  996. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  997. llvm::GlobalValue *GV) {
  998. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  999. // Get the struct elements for these annotations.
  1000. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1001. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1002. }
  1003. bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
  1004. // Never defer when EmitAllDecls is specified.
  1005. if (LangOpts.EmitAllDecls)
  1006. return false;
  1007. return !getContext().DeclMustBeEmitted(Global);
  1008. }
  1009. llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
  1010. const CXXUuidofExpr* E) {
  1011. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1012. // well-formed.
  1013. StringRef Uuid = E->getUuidAsStringRef(Context);
  1014. std::string Name = "_GUID_" + Uuid.lower();
  1015. std::replace(Name.begin(), Name.end(), '-', '_');
  1016. // Look for an existing global.
  1017. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1018. return GV;
  1019. llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
  1020. assert(Init && "failed to initialize as constant");
  1021. auto *GV = new llvm::GlobalVariable(
  1022. getModule(), Init->getType(),
  1023. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1024. return GV;
  1025. }
  1026. llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1027. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1028. assert(AA && "No alias?");
  1029. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1030. // See if there is already something with the target's name in the module.
  1031. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1032. if (Entry) {
  1033. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1034. return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1035. }
  1036. llvm::Constant *Aliasee;
  1037. if (isa<llvm::FunctionType>(DeclTy))
  1038. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1039. GlobalDecl(cast<FunctionDecl>(VD)),
  1040. /*ForVTable=*/false);
  1041. else
  1042. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1043. llvm::PointerType::getUnqual(DeclTy),
  1044. nullptr);
  1045. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1046. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1047. WeakRefReferences.insert(F);
  1048. return Aliasee;
  1049. }
  1050. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1051. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1052. // Weak references don't produce any output by themselves.
  1053. if (Global->hasAttr<WeakRefAttr>())
  1054. return;
  1055. // If this is an alias definition (which otherwise looks like a declaration)
  1056. // emit it now.
  1057. if (Global->hasAttr<AliasAttr>())
  1058. return EmitAliasDefinition(GD);
  1059. // If this is CUDA, be selective about which declarations we emit.
  1060. if (LangOpts.CUDA) {
  1061. if (CodeGenOpts.CUDAIsDevice) {
  1062. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1063. !Global->hasAttr<CUDAGlobalAttr>() &&
  1064. !Global->hasAttr<CUDAConstantAttr>() &&
  1065. !Global->hasAttr<CUDASharedAttr>())
  1066. return;
  1067. } else {
  1068. if (!Global->hasAttr<CUDAHostAttr>() && (
  1069. Global->hasAttr<CUDADeviceAttr>() ||
  1070. Global->hasAttr<CUDAConstantAttr>() ||
  1071. Global->hasAttr<CUDASharedAttr>()))
  1072. return;
  1073. }
  1074. }
  1075. // Ignore declarations, they will be emitted on their first use.
  1076. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1077. // Forward declarations are emitted lazily on first use.
  1078. if (!FD->doesThisDeclarationHaveABody()) {
  1079. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1080. return;
  1081. StringRef MangledName = getMangledName(GD);
  1082. // Compute the function info and LLVM type.
  1083. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1084. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1085. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1086. /*DontDefer=*/false);
  1087. return;
  1088. }
  1089. } else {
  1090. const auto *VD = cast<VarDecl>(Global);
  1091. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1092. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1093. !Context.isMSStaticDataMemberInlineDefinition(VD))
  1094. return;
  1095. }
  1096. // Defer code generation when possible if this is a static definition, inline
  1097. // function etc. These we only want to emit if they are used.
  1098. if (!MayDeferGeneration(Global)) {
  1099. // Emit the definition if it can't be deferred.
  1100. EmitGlobalDefinition(GD);
  1101. return;
  1102. }
  1103. // If we're deferring emission of a C++ variable with an
  1104. // initializer, remember the order in which it appeared in the file.
  1105. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1106. cast<VarDecl>(Global)->hasInit()) {
  1107. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1108. CXXGlobalInits.push_back(nullptr);
  1109. }
  1110. // If the value has already been used, add it directly to the
  1111. // DeferredDeclsToEmit list.
  1112. StringRef MangledName = getMangledName(GD);
  1113. if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
  1114. addDeferredDeclToEmit(GV, GD);
  1115. else {
  1116. // Otherwise, remember that we saw a deferred decl with this name. The
  1117. // first use of the mangled name will cause it to move into
  1118. // DeferredDeclsToEmit.
  1119. DeferredDecls[MangledName] = GD;
  1120. }
  1121. }
  1122. namespace {
  1123. struct FunctionIsDirectlyRecursive :
  1124. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1125. const StringRef Name;
  1126. const Builtin::Context &BI;
  1127. bool Result;
  1128. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1129. Name(N), BI(C), Result(false) {
  1130. }
  1131. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1132. bool TraverseCallExpr(CallExpr *E) {
  1133. const FunctionDecl *FD = E->getDirectCallee();
  1134. if (!FD)
  1135. return true;
  1136. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1137. if (Attr && Name == Attr->getLabel()) {
  1138. Result = true;
  1139. return false;
  1140. }
  1141. unsigned BuiltinID = FD->getBuiltinID();
  1142. if (!BuiltinID)
  1143. return true;
  1144. StringRef BuiltinName = BI.GetName(BuiltinID);
  1145. if (BuiltinName.startswith("__builtin_") &&
  1146. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1147. Result = true;
  1148. return false;
  1149. }
  1150. return true;
  1151. }
  1152. };
  1153. }
  1154. // isTriviallyRecursive - Check if this function calls another
  1155. // decl that, because of the asm attribute or the other decl being a builtin,
  1156. // ends up pointing to itself.
  1157. bool
  1158. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1159. StringRef Name;
  1160. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1161. // asm labels are a special kind of mangling we have to support.
  1162. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1163. if (!Attr)
  1164. return false;
  1165. Name = Attr->getLabel();
  1166. } else {
  1167. Name = FD->getName();
  1168. }
  1169. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1170. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1171. return Walker.Result;
  1172. }
  1173. bool
  1174. CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1175. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1176. return true;
  1177. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1178. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1179. return false;
  1180. // PR9614. Avoid cases where the source code is lying to us. An available
  1181. // externally function should have an equivalent function somewhere else,
  1182. // but a function that calls itself is clearly not equivalent to the real
  1183. // implementation.
  1184. // This happens in glibc's btowc and in some configure checks.
  1185. return !isTriviallyRecursive(F);
  1186. }
  1187. /// If the type for the method's class was generated by
  1188. /// CGDebugInfo::createContextChain(), the cache contains only a
  1189. /// limited DIType without any declarations. Since EmitFunctionStart()
  1190. /// needs to find the canonical declaration for each method, we need
  1191. /// to construct the complete type prior to emitting the method.
  1192. void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
  1193. if (!D->isInstance())
  1194. return;
  1195. if (CGDebugInfo *DI = getModuleDebugInfo())
  1196. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
  1197. const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
  1198. DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
  1199. }
  1200. }
  1201. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1202. const auto *D = cast<ValueDecl>(GD.getDecl());
  1203. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1204. Context.getSourceManager(),
  1205. "Generating code for declaration");
  1206. if (isa<FunctionDecl>(D)) {
  1207. // At -O0, don't generate IR for functions with available_externally
  1208. // linkage.
  1209. if (!shouldEmitFunction(GD))
  1210. return;
  1211. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1212. CompleteDIClassType(Method);
  1213. // Make sure to emit the definition(s) before we emit the thunks.
  1214. // This is necessary for the generation of certain thunks.
  1215. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1216. EmitCXXConstructor(CD, GD.getCtorType());
  1217. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1218. EmitCXXDestructor(DD, GD.getDtorType());
  1219. else
  1220. EmitGlobalFunctionDefinition(GD, GV);
  1221. if (Method->isVirtual())
  1222. getVTables().EmitThunks(GD);
  1223. return;
  1224. }
  1225. return EmitGlobalFunctionDefinition(GD, GV);
  1226. }
  1227. if (const auto *VD = dyn_cast<VarDecl>(D))
  1228. return EmitGlobalVarDefinition(VD);
  1229. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1230. }
  1231. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1232. /// module, create and return an llvm Function with the specified type. If there
  1233. /// is something in the module with the specified name, return it potentially
  1234. /// bitcasted to the right type.
  1235. ///
  1236. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1237. /// to set the attributes on the function when it is first created.
  1238. llvm::Constant *
  1239. CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
  1240. llvm::Type *Ty,
  1241. GlobalDecl GD, bool ForVTable,
  1242. bool DontDefer,
  1243. llvm::AttributeSet ExtraAttrs) {
  1244. const Decl *D = GD.getDecl();
  1245. // Lookup the entry, lazily creating it if necessary.
  1246. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1247. if (Entry) {
  1248. if (WeakRefReferences.erase(Entry)) {
  1249. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1250. if (FD && !FD->hasAttr<WeakAttr>())
  1251. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1252. }
  1253. // Handle dropped DLL attributes.
  1254. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1255. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1256. if (Entry->getType()->getElementType() == Ty)
  1257. return Entry;
  1258. // Make sure the result is of the correct type.
  1259. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1260. }
  1261. // This function doesn't have a complete type (for example, the return
  1262. // type is an incomplete struct). Use a fake type instead, and make
  1263. // sure not to try to set attributes.
  1264. bool IsIncompleteFunction = false;
  1265. llvm::FunctionType *FTy;
  1266. if (isa<llvm::FunctionType>(Ty)) {
  1267. FTy = cast<llvm::FunctionType>(Ty);
  1268. } else {
  1269. FTy = llvm::FunctionType::get(VoidTy, false);
  1270. IsIncompleteFunction = true;
  1271. }
  1272. llvm::Function *F = llvm::Function::Create(FTy,
  1273. llvm::Function::ExternalLinkage,
  1274. MangledName, &getModule());
  1275. assert(F->getName() == MangledName && "name was uniqued!");
  1276. if (D)
  1277. SetFunctionAttributes(GD, F, IsIncompleteFunction);
  1278. if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
  1279. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
  1280. F->addAttributes(llvm::AttributeSet::FunctionIndex,
  1281. llvm::AttributeSet::get(VMContext,
  1282. llvm::AttributeSet::FunctionIndex,
  1283. B));
  1284. }
  1285. if (!DontDefer) {
  1286. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1287. // each other bottoming out with the base dtor. Therefore we emit non-base
  1288. // dtors on usage, even if there is no dtor definition in the TU.
  1289. if (D && isa<CXXDestructorDecl>(D) &&
  1290. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1291. GD.getDtorType()))
  1292. addDeferredDeclToEmit(F, GD);
  1293. // This is the first use or definition of a mangled name. If there is a
  1294. // deferred decl with this name, remember that we need to emit it at the end
  1295. // of the file.
  1296. auto DDI = DeferredDecls.find(MangledName);
  1297. if (DDI != DeferredDecls.end()) {
  1298. // Move the potentially referenced deferred decl to the
  1299. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1300. // don't need it anymore).
  1301. addDeferredDeclToEmit(F, DDI->second);
  1302. DeferredDecls.erase(DDI);
  1303. // Otherwise, if this is a sized deallocation function, emit a weak
  1304. // definition
  1305. // for it at the end of the translation unit.
  1306. } else if (D && cast<FunctionDecl>(D)
  1307. ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
  1308. addDeferredDeclToEmit(F, GD);
  1309. // Otherwise, there are cases we have to worry about where we're
  1310. // using a declaration for which we must emit a definition but where
  1311. // we might not find a top-level definition:
  1312. // - member functions defined inline in their classes
  1313. // - friend functions defined inline in some class
  1314. // - special member functions with implicit definitions
  1315. // If we ever change our AST traversal to walk into class methods,
  1316. // this will be unnecessary.
  1317. //
  1318. // We also don't emit a definition for a function if it's going to be an
  1319. // entry in a vtable, unless it's already marked as used.
  1320. } else if (getLangOpts().CPlusPlus && D) {
  1321. // Look for a declaration that's lexically in a record.
  1322. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1323. FD = FD->getPreviousDecl()) {
  1324. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1325. if (FD->doesThisDeclarationHaveABody()) {
  1326. addDeferredDeclToEmit(F, GD.getWithDecl(FD));
  1327. break;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. // Make sure the result is of the requested type.
  1334. if (!IsIncompleteFunction) {
  1335. assert(F->getType()->getElementType() == Ty);
  1336. return F;
  1337. }
  1338. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1339. return llvm::ConstantExpr::getBitCast(F, PTy);
  1340. }
  1341. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1342. /// non-null, then this function will use the specified type if it has to
  1343. /// create it (this occurs when we see a definition of the function).
  1344. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1345. llvm::Type *Ty,
  1346. bool ForVTable,
  1347. bool DontDefer) {
  1348. // If there was no specific requested type, just convert it now.
  1349. if (!Ty)
  1350. Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
  1351. StringRef MangledName = getMangledName(GD);
  1352. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
  1353. }
  1354. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1355. /// type and name.
  1356. llvm::Constant *
  1357. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
  1358. StringRef Name,
  1359. llvm::AttributeSet ExtraAttrs) {
  1360. llvm::Constant *C =
  1361. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1362. /*DontDefer=*/false, ExtraAttrs);
  1363. if (auto *F = dyn_cast<llvm::Function>(C))
  1364. if (F->empty())
  1365. F->setCallingConv(getRuntimeCC());
  1366. return C;
  1367. }
  1368. /// isTypeConstant - Determine whether an object of this type can be emitted
  1369. /// as a constant.
  1370. ///
  1371. /// If ExcludeCtor is true, the duration when the object's constructor runs
  1372. /// will not be considered. The caller will need to verify that the object is
  1373. /// not written to during its construction.
  1374. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  1375. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  1376. return false;
  1377. if (Context.getLangOpts().CPlusPlus) {
  1378. if (const CXXRecordDecl *Record
  1379. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  1380. return ExcludeCtor && !Record->hasMutableFields() &&
  1381. Record->hasTrivialDestructor();
  1382. }
  1383. return true;
  1384. }
  1385. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  1386. /// create and return an llvm GlobalVariable with the specified type. If there
  1387. /// is something in the module with the specified name, return it potentially
  1388. /// bitcasted to the right type.
  1389. ///
  1390. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1391. /// to set the attributes on the global when it is first created.
  1392. llvm::Constant *
  1393. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  1394. llvm::PointerType *Ty,
  1395. const VarDecl *D) {
  1396. // Lookup the entry, lazily creating it if necessary.
  1397. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1398. if (Entry) {
  1399. if (WeakRefReferences.erase(Entry)) {
  1400. if (D && !D->hasAttr<WeakAttr>())
  1401. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1402. }
  1403. // Handle dropped DLL attributes.
  1404. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1405. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1406. if (Entry->getType() == Ty)
  1407. return Entry;
  1408. // Make sure the result is of the correct type.
  1409. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  1410. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  1411. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  1412. }
  1413. unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
  1414. auto *GV = new llvm::GlobalVariable(
  1415. getModule(), Ty->getElementType(), false,
  1416. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  1417. llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  1418. // This is the first use or definition of a mangled name. If there is a
  1419. // deferred decl with this name, remember that we need to emit it at the end
  1420. // of the file.
  1421. auto DDI = DeferredDecls.find(MangledName);
  1422. if (DDI != DeferredDecls.end()) {
  1423. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  1424. // list, and remove it from DeferredDecls (since we don't need it anymore).
  1425. addDeferredDeclToEmit(GV, DDI->second);
  1426. DeferredDecls.erase(DDI);
  1427. }
  1428. // Handle things which are present even on external declarations.
  1429. if (D) {
  1430. // FIXME: This code is overly simple and should be merged with other global
  1431. // handling.
  1432. GV->setConstant(isTypeConstant(D->getType(), false));
  1433. setLinkageAndVisibilityForGV(GV, D);
  1434. if (D->getTLSKind()) {
  1435. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  1436. CXXThreadLocals.push_back(std::make_pair(D, GV));
  1437. setTLSMode(GV, *D);
  1438. }
  1439. // If required by the ABI, treat declarations of static data members with
  1440. // inline initializers as definitions.
  1441. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  1442. EmitGlobalVarDefinition(D);
  1443. }
  1444. // Handle XCore specific ABI requirements.
  1445. if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
  1446. D->getLanguageLinkage() == CLanguageLinkage &&
  1447. D->getType().isConstant(Context) &&
  1448. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  1449. GV->setSection(".cp.rodata");
  1450. }
  1451. if (AddrSpace != Ty->getAddressSpace())
  1452. return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
  1453. return GV;
  1454. }
  1455. llvm::GlobalVariable *
  1456. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  1457. llvm::Type *Ty,
  1458. llvm::GlobalValue::LinkageTypes Linkage) {
  1459. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  1460. llvm::GlobalVariable *OldGV = nullptr;
  1461. if (GV) {
  1462. // Check if the variable has the right type.
  1463. if (GV->getType()->getElementType() == Ty)
  1464. return GV;
  1465. // Because C++ name mangling, the only way we can end up with an already
  1466. // existing global with the same name is if it has been declared extern "C".
  1467. assert(GV->isDeclaration() && "Declaration has wrong type!");
  1468. OldGV = GV;
  1469. }
  1470. // Create a new variable.
  1471. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  1472. Linkage, nullptr, Name);
  1473. if (OldGV) {
  1474. // Replace occurrences of the old variable if needed.
  1475. GV->takeName(OldGV);
  1476. if (!OldGV->use_empty()) {
  1477. llvm::Constant *NewPtrForOldDecl =
  1478. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  1479. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  1480. }
  1481. OldGV->eraseFromParent();
  1482. }
  1483. return GV;
  1484. }
  1485. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  1486. /// given global variable. If Ty is non-null and if the global doesn't exist,
  1487. /// then it will be created with the specified type instead of whatever the
  1488. /// normal requested type would be.
  1489. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  1490. llvm::Type *Ty) {
  1491. assert(D->hasGlobalStorage() && "Not a global variable");
  1492. QualType ASTTy = D->getType();
  1493. if (!Ty)
  1494. Ty = getTypes().ConvertTypeForMem(ASTTy);
  1495. llvm::PointerType *PTy =
  1496. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  1497. StringRef MangledName = getMangledName(D);
  1498. return GetOrCreateLLVMGlobal(MangledName, PTy, D);
  1499. }
  1500. /// CreateRuntimeVariable - Create a new runtime global variable with the
  1501. /// specified type and name.
  1502. llvm::Constant *
  1503. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  1504. StringRef Name) {
  1505. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  1506. }
  1507. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  1508. assert(!D->getInit() && "Cannot emit definite definitions here!");
  1509. if (MayDeferGeneration(D)) {
  1510. // If we have not seen a reference to this variable yet, place it
  1511. // into the deferred declarations table to be emitted if needed
  1512. // later.
  1513. StringRef MangledName = getMangledName(D);
  1514. if (!GetGlobalValue(MangledName)) {
  1515. DeferredDecls[MangledName] = D;
  1516. return;
  1517. }
  1518. }
  1519. // The tentative definition is the only definition.
  1520. EmitGlobalVarDefinition(D);
  1521. }
  1522. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  1523. return Context.toCharUnitsFromBits(
  1524. TheDataLayout.getTypeStoreSizeInBits(Ty));
  1525. }
  1526. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
  1527. unsigned AddrSpace) {
  1528. if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
  1529. if (D->hasAttr<CUDAConstantAttr>())
  1530. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
  1531. else if (D->hasAttr<CUDASharedAttr>())
  1532. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
  1533. else
  1534. AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
  1535. }
  1536. return AddrSpace;
  1537. }
  1538. template<typename SomeDecl>
  1539. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  1540. llvm::GlobalValue *GV) {
  1541. if (!getLangOpts().CPlusPlus)
  1542. return;
  1543. // Must have 'used' attribute, or else inline assembly can't rely on
  1544. // the name existing.
  1545. if (!D->template hasAttr<UsedAttr>())
  1546. return;
  1547. // Must have internal linkage and an ordinary name.
  1548. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  1549. return;
  1550. // Must be in an extern "C" context. Entities declared directly within
  1551. // a record are not extern "C" even if the record is in such a context.
  1552. const SomeDecl *First = D->getFirstDecl();
  1553. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  1554. return;
  1555. // OK, this is an internal linkage entity inside an extern "C" linkage
  1556. // specification. Make a note of that so we can give it the "expected"
  1557. // mangled name if nothing else is using that name.
  1558. std::pair<StaticExternCMap::iterator, bool> R =
  1559. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  1560. // If we have multiple internal linkage entities with the same name
  1561. // in extern "C" regions, none of them gets that name.
  1562. if (!R.second)
  1563. R.first->second = nullptr;
  1564. }
  1565. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
  1566. llvm::Constant *Init = nullptr;
  1567. QualType ASTTy = D->getType();
  1568. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  1569. bool NeedsGlobalCtor = false;
  1570. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  1571. const VarDecl *InitDecl;
  1572. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  1573. if (!InitExpr) {
  1574. // This is a tentative definition; tentative definitions are
  1575. // implicitly initialized with { 0 }.
  1576. //
  1577. // Note that tentative definitions are only emitted at the end of
  1578. // a translation unit, so they should never have incomplete
  1579. // type. In addition, EmitTentativeDefinition makes sure that we
  1580. // never attempt to emit a tentative definition if a real one
  1581. // exists. A use may still exists, however, so we still may need
  1582. // to do a RAUW.
  1583. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  1584. Init = EmitNullConstant(D->getType());
  1585. } else {
  1586. initializedGlobalDecl = GlobalDecl(D);
  1587. Init = EmitConstantInit(*InitDecl);
  1588. if (!Init) {
  1589. QualType T = InitExpr->getType();
  1590. if (D->getType()->isReferenceType())
  1591. T = D->getType();
  1592. if (getLangOpts().CPlusPlus) {
  1593. Init = EmitNullConstant(T);
  1594. NeedsGlobalCtor = true;
  1595. } else {
  1596. ErrorUnsupported(D, "static initializer");
  1597. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  1598. }
  1599. } else {
  1600. // We don't need an initializer, so remove the entry for the delayed
  1601. // initializer position (just in case this entry was delayed) if we
  1602. // also don't need to register a destructor.
  1603. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  1604. DelayedCXXInitPosition.erase(D);
  1605. }
  1606. }
  1607. llvm::Type* InitType = Init->getType();
  1608. llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
  1609. // Strip off a bitcast if we got one back.
  1610. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  1611. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  1612. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  1613. // All zero index gep.
  1614. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  1615. Entry = CE->getOperand(0);
  1616. }
  1617. // Entry is now either a Function or GlobalVariable.
  1618. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  1619. // We have a definition after a declaration with the wrong type.
  1620. // We must make a new GlobalVariable* and update everything that used OldGV
  1621. // (a declaration or tentative definition) with the new GlobalVariable*
  1622. // (which will be a definition).
  1623. //
  1624. // This happens if there is a prototype for a global (e.g.
  1625. // "extern int x[];") and then a definition of a different type (e.g.
  1626. // "int x[10];"). This also happens when an initializer has a different type
  1627. // from the type of the global (this happens with unions).
  1628. if (!GV ||
  1629. GV->getType()->getElementType() != InitType ||
  1630. GV->getType()->getAddressSpace() !=
  1631. GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
  1632. // Move the old entry aside so that we'll create a new one.
  1633. Entry->setName(StringRef());
  1634. // Make a new global with the correct type, this is now guaranteed to work.
  1635. GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
  1636. // Replace all uses of the old global with the new global
  1637. llvm::Constant *NewPtrForOldDecl =
  1638. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  1639. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  1640. // Erase the old global, since it is no longer used.
  1641. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  1642. }
  1643. MaybeHandleStaticInExternC(D, GV);
  1644. if (D->hasAttr<AnnotateAttr>())
  1645. AddGlobalAnnotations(D, GV);
  1646. GV->setInitializer(Init);
  1647. // If it is safe to mark the global 'constant', do so now.
  1648. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  1649. isTypeConstant(D->getType(), true));
  1650. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  1651. // Set the llvm linkage type as appropriate.
  1652. llvm::GlobalValue::LinkageTypes Linkage =
  1653. getLLVMLinkageVarDefinition(D, GV->isConstant());
  1654. // On Darwin, the backing variable for a C++11 thread_local variable always
  1655. // has internal linkage; all accesses should just be calls to the
  1656. // Itanium-specified entry point, which has the normal linkage of the
  1657. // variable.
  1658. if (const auto *VD = dyn_cast<VarDecl>(D))
  1659. if (!VD->isStaticLocal() && VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  1660. Context.getTargetInfo().getTriple().isMacOSX())
  1661. Linkage = llvm::GlobalValue::InternalLinkage;
  1662. GV->setLinkage(Linkage);
  1663. if (D->hasAttr<DLLImportAttr>())
  1664. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  1665. else if (D->hasAttr<DLLExportAttr>())
  1666. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  1667. if (Linkage == llvm::GlobalVariable::CommonLinkage)
  1668. // common vars aren't constant even if declared const.
  1669. GV->setConstant(false);
  1670. setNonAliasAttributes(D, GV);
  1671. // Emit the initializer function if necessary.
  1672. if (NeedsGlobalCtor || NeedsGlobalDtor)
  1673. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  1674. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  1675. // Emit global variable debug information.
  1676. if (CGDebugInfo *DI = getModuleDebugInfo())
  1677. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1678. DI->EmitGlobalVariable(GV, D);
  1679. }
  1680. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  1681. const VarDecl *D, bool NoCommon) {
  1682. // Don't give variables common linkage if -fno-common was specified unless it
  1683. // was overridden by a NoCommon attribute.
  1684. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  1685. return true;
  1686. // C11 6.9.2/2:
  1687. // A declaration of an identifier for an object that has file scope without
  1688. // an initializer, and without a storage-class specifier or with the
  1689. // storage-class specifier static, constitutes a tentative definition.
  1690. if (D->getInit() || D->hasExternalStorage())
  1691. return true;
  1692. // A variable cannot be both common and exist in a section.
  1693. if (D->hasAttr<SectionAttr>())
  1694. return true;
  1695. // Thread local vars aren't considered common linkage.
  1696. if (D->getTLSKind())
  1697. return true;
  1698. // Tentative definitions marked with WeakImportAttr are true definitions.
  1699. if (D->hasAttr<WeakImportAttr>())
  1700. return true;
  1701. // Declarations with a required alignment do not have common linakge in MSVC
  1702. // mode.
  1703. if (Context.getLangOpts().MSVCCompat &&
  1704. (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>()))
  1705. return true;
  1706. return false;
  1707. }
  1708. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  1709. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  1710. if (Linkage == GVA_Internal)
  1711. return llvm::Function::InternalLinkage;
  1712. if (D->hasAttr<WeakAttr>()) {
  1713. if (IsConstantVariable)
  1714. return llvm::GlobalVariable::WeakODRLinkage;
  1715. else
  1716. return llvm::GlobalVariable::WeakAnyLinkage;
  1717. }
  1718. // We are guaranteed to have a strong definition somewhere else,
  1719. // so we can use available_externally linkage.
  1720. if (Linkage == GVA_AvailableExternally)
  1721. return llvm::Function::AvailableExternallyLinkage;
  1722. // Note that Apple's kernel linker doesn't support symbol
  1723. // coalescing, so we need to avoid linkonce and weak linkages there.
  1724. // Normally, this means we just map to internal, but for explicit
  1725. // instantiations we'll map to external.
  1726. // In C++, the compiler has to emit a definition in every translation unit
  1727. // that references the function. We should use linkonce_odr because
  1728. // a) if all references in this translation unit are optimized away, we
  1729. // don't need to codegen it. b) if the function persists, it needs to be
  1730. // merged with other definitions. c) C++ has the ODR, so we know the
  1731. // definition is dependable.
  1732. if (Linkage == GVA_DiscardableODR)
  1733. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  1734. : llvm::Function::InternalLinkage;
  1735. // An explicit instantiation of a template has weak linkage, since
  1736. // explicit instantiations can occur in multiple translation units
  1737. // and must all be equivalent. However, we are not allowed to
  1738. // throw away these explicit instantiations.
  1739. if (Linkage == GVA_StrongODR)
  1740. return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
  1741. : llvm::Function::ExternalLinkage;
  1742. // C++ doesn't have tentative definitions and thus cannot have common
  1743. // linkage.
  1744. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  1745. !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
  1746. CodeGenOpts.NoCommon))
  1747. return llvm::GlobalVariable::CommonLinkage;
  1748. // selectany symbols are externally visible, so use weak instead of
  1749. // linkonce. MSVC optimizes away references to const selectany globals, so
  1750. // all definitions should be the same and ODR linkage should be used.
  1751. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  1752. if (D->hasAttr<SelectAnyAttr>())
  1753. return llvm::GlobalVariable::WeakODRLinkage;
  1754. // Otherwise, we have strong external linkage.
  1755. assert(Linkage == GVA_StrongExternal);
  1756. return llvm::GlobalVariable::ExternalLinkage;
  1757. }
  1758. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  1759. const VarDecl *VD, bool IsConstant) {
  1760. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  1761. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  1762. }
  1763. /// Replace the uses of a function that was declared with a non-proto type.
  1764. /// We want to silently drop extra arguments from call sites
  1765. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  1766. llvm::Function *newFn) {
  1767. // Fast path.
  1768. if (old->use_empty()) return;
  1769. llvm::Type *newRetTy = newFn->getReturnType();
  1770. SmallVector<llvm::Value*, 4> newArgs;
  1771. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  1772. ui != ue; ) {
  1773. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  1774. llvm::User *user = use->getUser();
  1775. // Recognize and replace uses of bitcasts. Most calls to
  1776. // unprototyped functions will use bitcasts.
  1777. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  1778. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  1779. replaceUsesOfNonProtoConstant(bitcast, newFn);
  1780. continue;
  1781. }
  1782. // Recognize calls to the function.
  1783. llvm::CallSite callSite(user);
  1784. if (!callSite) continue;
  1785. if (!callSite.isCallee(&*use)) continue;
  1786. // If the return types don't match exactly, then we can't
  1787. // transform this call unless it's dead.
  1788. if (callSite->getType() != newRetTy && !callSite->use_empty())
  1789. continue;
  1790. // Get the call site's attribute list.
  1791. SmallVector<llvm::AttributeSet, 8> newAttrs;
  1792. llvm::AttributeSet oldAttrs = callSite.getAttributes();
  1793. // Collect any return attributes from the call.
  1794. if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
  1795. newAttrs.push_back(
  1796. llvm::AttributeSet::get(newFn->getContext(),
  1797. oldAttrs.getRetAttributes()));
  1798. // If the function was passed too few arguments, don't transform.
  1799. unsigned newNumArgs = newFn->arg_size();
  1800. if (callSite.arg_size() < newNumArgs) continue;
  1801. // If extra arguments were passed, we silently drop them.
  1802. // If any of the types mismatch, we don't transform.
  1803. unsigned argNo = 0;
  1804. bool dontTransform = false;
  1805. for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
  1806. ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
  1807. if (callSite.getArgument(argNo)->getType() != ai->getType()) {
  1808. dontTransform = true;
  1809. break;
  1810. }
  1811. // Add any parameter attributes.
  1812. if (oldAttrs.hasAttributes(argNo + 1))
  1813. newAttrs.
  1814. push_back(llvm::
  1815. AttributeSet::get(newFn->getContext(),
  1816. oldAttrs.getParamAttributes(argNo + 1)));
  1817. }
  1818. if (dontTransform)
  1819. continue;
  1820. if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
  1821. newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
  1822. oldAttrs.getFnAttributes()));
  1823. // Okay, we can transform this. Create the new call instruction and copy
  1824. // over the required information.
  1825. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  1826. llvm::CallSite newCall;
  1827. if (callSite.isCall()) {
  1828. newCall = llvm::CallInst::Create(newFn, newArgs, "",
  1829. callSite.getInstruction());
  1830. } else {
  1831. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  1832. newCall = llvm::InvokeInst::Create(newFn,
  1833. oldInvoke->getNormalDest(),
  1834. oldInvoke->getUnwindDest(),
  1835. newArgs, "",
  1836. callSite.getInstruction());
  1837. }
  1838. newArgs.clear(); // for the next iteration
  1839. if (!newCall->getType()->isVoidTy())
  1840. newCall->takeName(callSite.getInstruction());
  1841. newCall.setAttributes(
  1842. llvm::AttributeSet::get(newFn->getContext(), newAttrs));
  1843. newCall.setCallingConv(callSite.getCallingConv());
  1844. // Finally, remove the old call, replacing any uses with the new one.
  1845. if (!callSite->use_empty())
  1846. callSite->replaceAllUsesWith(newCall.getInstruction());
  1847. // Copy debug location attached to CI.
  1848. if (!callSite->getDebugLoc().isUnknown())
  1849. newCall->setDebugLoc(callSite->getDebugLoc());
  1850. callSite->eraseFromParent();
  1851. }
  1852. }
  1853. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  1854. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  1855. /// existing call uses of the old function in the module, this adjusts them to
  1856. /// call the new function directly.
  1857. ///
  1858. /// This is not just a cleanup: the always_inline pass requires direct calls to
  1859. /// functions to be able to inline them. If there is a bitcast in the way, it
  1860. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  1861. /// run at -O0.
  1862. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1863. llvm::Function *NewFn) {
  1864. // If we're redefining a global as a function, don't transform it.
  1865. if (!isa<llvm::Function>(Old)) return;
  1866. replaceUsesOfNonProtoConstant(Old, NewFn);
  1867. }
  1868. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  1869. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  1870. // If we have a definition, this might be a deferred decl. If the
  1871. // instantiation is explicit, make sure we emit it at the end.
  1872. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  1873. GetAddrOfGlobalVar(VD);
  1874. EmitTopLevelDecl(VD);
  1875. }
  1876. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  1877. llvm::GlobalValue *GV) {
  1878. const auto *D = cast<FunctionDecl>(GD.getDecl());
  1879. // Compute the function info and LLVM type.
  1880. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1881. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  1882. // Get or create the prototype for the function.
  1883. if (!GV) {
  1884. llvm::Constant *C =
  1885. GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
  1886. // Strip off a bitcast if we got one back.
  1887. if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
  1888. assert(CE->getOpcode() == llvm::Instruction::BitCast);
  1889. GV = cast<llvm::GlobalValue>(CE->getOperand(0));
  1890. } else {
  1891. GV = cast<llvm::GlobalValue>(C);
  1892. }
  1893. }
  1894. if (!GV->isDeclaration()) {
  1895. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
  1896. GlobalDecl OldGD = Manglings.lookup(GV->getName());
  1897. if (auto *Prev = OldGD.getDecl())
  1898. getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
  1899. return;
  1900. }
  1901. if (GV->getType()->getElementType() != Ty) {
  1902. // If the types mismatch then we have to rewrite the definition.
  1903. assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
  1904. // F is the Function* for the one with the wrong type, we must make a new
  1905. // Function* and update everything that used F (a declaration) with the new
  1906. // Function* (which will be a definition).
  1907. //
  1908. // This happens if there is a prototype for a function
  1909. // (e.g. "int f()") and then a definition of a different type
  1910. // (e.g. "int f(int x)"). Move the old function aside so that it
  1911. // doesn't interfere with GetAddrOfFunction.
  1912. GV->setName(StringRef());
  1913. auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
  1914. // This might be an implementation of a function without a
  1915. // prototype, in which case, try to do special replacement of
  1916. // calls which match the new prototype. The really key thing here
  1917. // is that we also potentially drop arguments from the call site
  1918. // so as to make a direct call, which makes the inliner happier
  1919. // and suppresses a number of optimizer warnings (!) about
  1920. // dropping arguments.
  1921. if (!GV->use_empty()) {
  1922. ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
  1923. GV->removeDeadConstantUsers();
  1924. }
  1925. // Replace uses of F with the Function we will endow with a body.
  1926. if (!GV->use_empty()) {
  1927. llvm::Constant *NewPtrForOldDecl =
  1928. llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
  1929. GV->replaceAllUsesWith(NewPtrForOldDecl);
  1930. }
  1931. // Ok, delete the old function now, which is dead.
  1932. GV->eraseFromParent();
  1933. GV = NewFn;
  1934. }
  1935. // We need to set linkage and visibility on the function before
  1936. // generating code for it because various parts of IR generation
  1937. // want to propagate this information down (e.g. to local static
  1938. // declarations).
  1939. auto *Fn = cast<llvm::Function>(GV);
  1940. setFunctionLinkage(GD, Fn);
  1941. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  1942. setGlobalVisibility(Fn, D);
  1943. MaybeHandleStaticInExternC(D, Fn);
  1944. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  1945. setFunctionDefinitionAttributes(D, Fn);
  1946. SetLLVMFunctionAttributesForDefinition(D, Fn);
  1947. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  1948. AddGlobalCtor(Fn, CA->getPriority());
  1949. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  1950. AddGlobalDtor(Fn, DA->getPriority());
  1951. if (D->hasAttr<AnnotateAttr>())
  1952. AddGlobalAnnotations(D, Fn);
  1953. }
  1954. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  1955. const auto *D = cast<ValueDecl>(GD.getDecl());
  1956. const AliasAttr *AA = D->getAttr<AliasAttr>();
  1957. assert(AA && "Not an alias?");
  1958. StringRef MangledName = getMangledName(GD);
  1959. // If there is a definition in the module, then it wins over the alias.
  1960. // This is dubious, but allow it to be safe. Just ignore the alias.
  1961. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1962. if (Entry && !Entry->isDeclaration())
  1963. return;
  1964. Aliases.push_back(GD);
  1965. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  1966. // Create a reference to the named value. This ensures that it is emitted
  1967. // if a deferred decl.
  1968. llvm::Constant *Aliasee;
  1969. if (isa<llvm::FunctionType>(DeclTy))
  1970. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  1971. /*ForVTable=*/false);
  1972. else
  1973. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1974. llvm::PointerType::getUnqual(DeclTy),
  1975. nullptr);
  1976. // Create the new alias itself, but don't set a name yet.
  1977. auto *GA = llvm::GlobalAlias::create(
  1978. cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
  1979. llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  1980. if (Entry) {
  1981. if (GA->getAliasee() == Entry) {
  1982. Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
  1983. return;
  1984. }
  1985. assert(Entry->isDeclaration());
  1986. // If there is a declaration in the module, then we had an extern followed
  1987. // by the alias, as in:
  1988. // extern int test6();
  1989. // ...
  1990. // int test6() __attribute__((alias("test7")));
  1991. //
  1992. // Remove it and replace uses of it with the alias.
  1993. GA->takeName(Entry);
  1994. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  1995. Entry->getType()));
  1996. Entry->eraseFromParent();
  1997. } else {
  1998. GA->setName(MangledName);
  1999. }
  2000. // Set attributes which are particular to an alias; this is a
  2001. // specialization of the attributes which may be set on a global
  2002. // variable/function.
  2003. if (D->hasAttr<DLLExportAttr>()) {
  2004. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2005. // The dllexport attribute is ignored for undefined symbols.
  2006. if (FD->hasBody())
  2007. GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  2008. } else {
  2009. GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  2010. }
  2011. } else if (D->hasAttr<WeakAttr>() ||
  2012. D->hasAttr<WeakRefAttr>() ||
  2013. D->isWeakImported()) {
  2014. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2015. }
  2016. SetCommonAttributes(D, GA);
  2017. }
  2018. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2019. ArrayRef<llvm::Type*> Tys) {
  2020. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2021. Tys);
  2022. }
  2023. static llvm::StringMapEntry<llvm::Constant*> &
  2024. GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  2025. const StringLiteral *Literal,
  2026. bool TargetIsLSB,
  2027. bool &IsUTF16,
  2028. unsigned &StringLength) {
  2029. StringRef String = Literal->getString();
  2030. unsigned NumBytes = String.size();
  2031. // Check for simple case.
  2032. if (!Literal->containsNonAsciiOrNull()) {
  2033. StringLength = NumBytes;
  2034. return Map.GetOrCreateValue(String);
  2035. }
  2036. // Otherwise, convert the UTF8 literals into a string of shorts.
  2037. IsUTF16 = true;
  2038. SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2039. const UTF8 *FromPtr = (const UTF8 *)String.data();
  2040. UTF16 *ToPtr = &ToBuf[0];
  2041. (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  2042. &ToPtr, ToPtr + NumBytes,
  2043. strictConversion);
  2044. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2045. StringLength = ToPtr - &ToBuf[0];
  2046. // Add an explicit null.
  2047. *ToPtr = 0;
  2048. return Map.
  2049. GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2050. (StringLength + 1) * 2));
  2051. }
  2052. static llvm::StringMapEntry<llvm::Constant*> &
  2053. GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
  2054. const StringLiteral *Literal,
  2055. unsigned &StringLength) {
  2056. StringRef String = Literal->getString();
  2057. StringLength = String.size();
  2058. return Map.GetOrCreateValue(String);
  2059. }
  2060. llvm::Constant *
  2061. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2062. unsigned StringLength = 0;
  2063. bool isUTF16 = false;
  2064. llvm::StringMapEntry<llvm::Constant*> &Entry =
  2065. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2066. getDataLayout().isLittleEndian(),
  2067. isUTF16, StringLength);
  2068. if (llvm::Constant *C = Entry.getValue())
  2069. return C;
  2070. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2071. llvm::Constant *Zeros[] = { Zero, Zero };
  2072. llvm::Value *V;
  2073. // If we don't already have it, get __CFConstantStringClassReference.
  2074. if (!CFConstantStringClassRef) {
  2075. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2076. Ty = llvm::ArrayType::get(Ty, 0);
  2077. llvm::Constant *GV = CreateRuntimeVariable(Ty,
  2078. "__CFConstantStringClassReference");
  2079. // Decay array -> ptr
  2080. V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2081. CFConstantStringClassRef = V;
  2082. }
  2083. else
  2084. V = CFConstantStringClassRef;
  2085. QualType CFTy = getContext().getCFConstantStringType();
  2086. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2087. llvm::Constant *Fields[4];
  2088. // Class pointer.
  2089. Fields[0] = cast<llvm::ConstantExpr>(V);
  2090. // Flags.
  2091. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2092. Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
  2093. llvm::ConstantInt::get(Ty, 0x07C8);
  2094. // String pointer.
  2095. llvm::Constant *C = nullptr;
  2096. if (isUTF16) {
  2097. ArrayRef<uint16_t> Arr =
  2098. llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
  2099. const_cast<char *>(Entry.getKey().data())),
  2100. Entry.getKey().size() / 2);
  2101. C = llvm::ConstantDataArray::get(VMContext, Arr);
  2102. } else {
  2103. C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  2104. }
  2105. // Note: -fwritable-strings doesn't make the backing store strings of
  2106. // CFStrings writable. (See <rdar://problem/10657500>)
  2107. auto *GV =
  2108. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  2109. llvm::GlobalValue::PrivateLinkage, C, ".str");
  2110. GV->setUnnamedAddr(true);
  2111. // Don't enforce the target's minimum global alignment, since the only use
  2112. // of the string is via this class initializer.
  2113. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
  2114. // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
  2115. // that changes the section it ends in, which surprises ld64.
  2116. if (isUTF16) {
  2117. CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
  2118. GV->setAlignment(Align.getQuantity());
  2119. GV->setSection("__TEXT,__ustring");
  2120. } else {
  2121. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2122. GV->setAlignment(Align.getQuantity());
  2123. GV->setSection("__TEXT,__cstring,cstring_literals");
  2124. }
  2125. // String.
  2126. Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2127. if (isUTF16)
  2128. // Cast the UTF16 string to the correct type.
  2129. Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
  2130. // String length.
  2131. Ty = getTypes().ConvertType(getContext().LongTy);
  2132. Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
  2133. // The struct.
  2134. C = llvm::ConstantStruct::get(STy, Fields);
  2135. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2136. llvm::GlobalVariable::PrivateLinkage, C,
  2137. "_unnamed_cfstring_");
  2138. GV->setSection("__DATA,__cfstring");
  2139. Entry.setValue(GV);
  2140. return GV;
  2141. }
  2142. llvm::Constant *
  2143. CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
  2144. unsigned StringLength = 0;
  2145. llvm::StringMapEntry<llvm::Constant*> &Entry =
  2146. GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
  2147. if (llvm::Constant *C = Entry.getValue())
  2148. return C;
  2149. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2150. llvm::Constant *Zeros[] = { Zero, Zero };
  2151. llvm::Value *V;
  2152. // If we don't already have it, get _NSConstantStringClassReference.
  2153. if (!ConstantStringClassRef) {
  2154. std::string StringClass(getLangOpts().ObjCConstantStringClass);
  2155. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2156. llvm::Constant *GV;
  2157. if (LangOpts.ObjCRuntime.isNonFragile()) {
  2158. std::string str =
  2159. StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
  2160. : "OBJC_CLASS_$_" + StringClass;
  2161. GV = getObjCRuntime().GetClassGlobal(str);
  2162. // Make sure the result is of the correct type.
  2163. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2164. V = llvm::ConstantExpr::getBitCast(GV, PTy);
  2165. ConstantStringClassRef = V;
  2166. } else {
  2167. std::string str =
  2168. StringClass.empty() ? "_NSConstantStringClassReference"
  2169. : "_" + StringClass + "ClassReference";
  2170. llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
  2171. GV = CreateRuntimeVariable(PTy, str);
  2172. // Decay array -> ptr
  2173. V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2174. ConstantStringClassRef = V;
  2175. }
  2176. }
  2177. else
  2178. V = ConstantStringClassRef;
  2179. if (!NSConstantStringType) {
  2180. // Construct the type for a constant NSString.
  2181. RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
  2182. D->startDefinition();
  2183. QualType FieldTypes[3];
  2184. // const int *isa;
  2185. FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
  2186. // const char *str;
  2187. FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
  2188. // unsigned int length;
  2189. FieldTypes[2] = Context.UnsignedIntTy;
  2190. // Create fields
  2191. for (unsigned i = 0; i < 3; ++i) {
  2192. FieldDecl *Field = FieldDecl::Create(Context, D,
  2193. SourceLocation(),
  2194. SourceLocation(), nullptr,
  2195. FieldTypes[i], /*TInfo=*/nullptr,
  2196. /*BitWidth=*/nullptr,
  2197. /*Mutable=*/false,
  2198. ICIS_NoInit);
  2199. Field->setAccess(AS_public);
  2200. D->addDecl(Field);
  2201. }
  2202. D->completeDefinition();
  2203. QualType NSTy = Context.getTagDeclType(D);
  2204. NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
  2205. }
  2206. llvm::Constant *Fields[3];
  2207. // Class pointer.
  2208. Fields[0] = cast<llvm::ConstantExpr>(V);
  2209. // String pointer.
  2210. llvm::Constant *C =
  2211. llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
  2212. llvm::GlobalValue::LinkageTypes Linkage;
  2213. bool isConstant;
  2214. Linkage = llvm::GlobalValue::PrivateLinkage;
  2215. isConstant = !LangOpts.WritableStrings;
  2216. auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
  2217. Linkage, C, ".str");
  2218. GV->setUnnamedAddr(true);
  2219. // Don't enforce the target's minimum global alignment, since the only use
  2220. // of the string is via this class initializer.
  2221. CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
  2222. GV->setAlignment(Align.getQuantity());
  2223. Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
  2224. // String length.
  2225. llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
  2226. Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
  2227. // The struct.
  2228. C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
  2229. GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
  2230. llvm::GlobalVariable::PrivateLinkage, C,
  2231. "_unnamed_nsstring_");
  2232. const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
  2233. const char *NSStringNonFragileABISection =
  2234. "__DATA,__objc_stringobj,regular,no_dead_strip";
  2235. // FIXME. Fix section.
  2236. GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
  2237. ? NSStringNonFragileABISection
  2238. : NSStringSection);
  2239. Entry.setValue(GV);
  2240. return GV;
  2241. }
  2242. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  2243. if (ObjCFastEnumerationStateType.isNull()) {
  2244. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  2245. D->startDefinition();
  2246. QualType FieldTypes[] = {
  2247. Context.UnsignedLongTy,
  2248. Context.getPointerType(Context.getObjCIdType()),
  2249. Context.getPointerType(Context.UnsignedLongTy),
  2250. Context.getConstantArrayType(Context.UnsignedLongTy,
  2251. llvm::APInt(32, 5), ArrayType::Normal, 0)
  2252. };
  2253. for (size_t i = 0; i < 4; ++i) {
  2254. FieldDecl *Field = FieldDecl::Create(Context,
  2255. D,
  2256. SourceLocation(),
  2257. SourceLocation(), nullptr,
  2258. FieldTypes[i], /*TInfo=*/nullptr,
  2259. /*BitWidth=*/nullptr,
  2260. /*Mutable=*/false,
  2261. ICIS_NoInit);
  2262. Field->setAccess(AS_public);
  2263. D->addDecl(Field);
  2264. }
  2265. D->completeDefinition();
  2266. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  2267. }
  2268. return ObjCFastEnumerationStateType;
  2269. }
  2270. llvm::Constant *
  2271. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  2272. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  2273. // Don't emit it as the address of the string, emit the string data itself
  2274. // as an inline array.
  2275. if (E->getCharByteWidth() == 1) {
  2276. SmallString<64> Str(E->getString());
  2277. // Resize the string to the right size, which is indicated by its type.
  2278. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  2279. Str.resize(CAT->getSize().getZExtValue());
  2280. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  2281. }
  2282. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  2283. llvm::Type *ElemTy = AType->getElementType();
  2284. unsigned NumElements = AType->getNumElements();
  2285. // Wide strings have either 2-byte or 4-byte elements.
  2286. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  2287. SmallVector<uint16_t, 32> Elements;
  2288. Elements.reserve(NumElements);
  2289. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2290. Elements.push_back(E->getCodeUnit(i));
  2291. Elements.resize(NumElements);
  2292. return llvm::ConstantDataArray::get(VMContext, Elements);
  2293. }
  2294. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  2295. SmallVector<uint32_t, 32> Elements;
  2296. Elements.reserve(NumElements);
  2297. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  2298. Elements.push_back(E->getCodeUnit(i));
  2299. Elements.resize(NumElements);
  2300. return llvm::ConstantDataArray::get(VMContext, Elements);
  2301. }
  2302. static llvm::GlobalVariable *
  2303. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  2304. CodeGenModule &CGM, StringRef GlobalName,
  2305. unsigned Alignment) {
  2306. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  2307. unsigned AddrSpace = 0;
  2308. if (CGM.getLangOpts().OpenCL)
  2309. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  2310. // Create a global variable for this string
  2311. auto *GV = new llvm::GlobalVariable(
  2312. CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C,
  2313. GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  2314. GV->setAlignment(Alignment);
  2315. GV->setUnnamedAddr(true);
  2316. return GV;
  2317. }
  2318. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  2319. /// constant array for the given string literal.
  2320. llvm::GlobalVariable *
  2321. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
  2322. auto Alignment =
  2323. getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
  2324. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  2325. llvm::GlobalVariable **Entry = nullptr;
  2326. if (!LangOpts.WritableStrings) {
  2327. Entry = &ConstantStringMap[C];
  2328. if (auto GV = *Entry) {
  2329. if (Alignment > GV->getAlignment())
  2330. GV->setAlignment(Alignment);
  2331. return GV;
  2332. }
  2333. }
  2334. SmallString<256> MangledNameBuffer;
  2335. StringRef GlobalVariableName;
  2336. llvm::GlobalValue::LinkageTypes LT;
  2337. // Mangle the string literal if the ABI allows for it. However, we cannot
  2338. // do this if we are compiling with ASan or -fwritable-strings because they
  2339. // rely on strings having normal linkage.
  2340. if (!LangOpts.WritableStrings && !LangOpts.Sanitize.Address &&
  2341. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  2342. llvm::raw_svector_ostream Out(MangledNameBuffer);
  2343. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  2344. Out.flush();
  2345. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  2346. GlobalVariableName = MangledNameBuffer;
  2347. } else {
  2348. LT = llvm::GlobalValue::PrivateLinkage;
  2349. GlobalVariableName = ".str";
  2350. }
  2351. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  2352. if (Entry)
  2353. *Entry = GV;
  2354. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>");
  2355. return GV;
  2356. }
  2357. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  2358. /// array for the given ObjCEncodeExpr node.
  2359. llvm::GlobalVariable *
  2360. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  2361. std::string Str;
  2362. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  2363. return GetAddrOfConstantCString(Str);
  2364. }
  2365. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  2366. /// the literal and a terminating '\0' character.
  2367. /// The result has pointer to array type.
  2368. llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
  2369. const std::string &Str, const char *GlobalName, unsigned Alignment) {
  2370. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  2371. if (Alignment == 0) {
  2372. Alignment = getContext()
  2373. .getAlignOfGlobalVarInChars(getContext().CharTy)
  2374. .getQuantity();
  2375. }
  2376. llvm::Constant *C =
  2377. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  2378. // Don't share any string literals if strings aren't constant.
  2379. llvm::GlobalVariable **Entry = nullptr;
  2380. if (!LangOpts.WritableStrings) {
  2381. Entry = &ConstantStringMap[C];
  2382. if (auto GV = *Entry) {
  2383. if (Alignment > GV->getAlignment())
  2384. GV->setAlignment(Alignment);
  2385. return GV;
  2386. }
  2387. }
  2388. // Get the default prefix if a name wasn't specified.
  2389. if (!GlobalName)
  2390. GlobalName = ".str";
  2391. // Create a global variable for this.
  2392. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  2393. GlobalName, Alignment);
  2394. if (Entry)
  2395. *Entry = GV;
  2396. return GV;
  2397. }
  2398. llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
  2399. const MaterializeTemporaryExpr *E, const Expr *Init) {
  2400. assert((E->getStorageDuration() == SD_Static ||
  2401. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  2402. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  2403. // If we're not materializing a subobject of the temporary, keep the
  2404. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  2405. QualType MaterializedType = Init->getType();
  2406. if (Init == E->GetTemporaryExpr())
  2407. MaterializedType = E->getType();
  2408. llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
  2409. if (Slot)
  2410. return Slot;
  2411. // FIXME: If an externally-visible declaration extends multiple temporaries,
  2412. // we need to give each temporary the same name in every translation unit (and
  2413. // we also need to make the temporaries externally-visible).
  2414. SmallString<256> Name;
  2415. llvm::raw_svector_ostream Out(Name);
  2416. getCXXABI().getMangleContext().mangleReferenceTemporary(
  2417. VD, E->getManglingNumber(), Out);
  2418. Out.flush();
  2419. APValue *Value = nullptr;
  2420. if (E->getStorageDuration() == SD_Static) {
  2421. // We might have a cached constant initializer for this temporary. Note
  2422. // that this might have a different value from the value computed by
  2423. // evaluating the initializer if the surrounding constant expression
  2424. // modifies the temporary.
  2425. Value = getContext().getMaterializedTemporaryValue(E, false);
  2426. if (Value && Value->isUninit())
  2427. Value = nullptr;
  2428. }
  2429. // Try evaluating it now, it might have a constant initializer.
  2430. Expr::EvalResult EvalResult;
  2431. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  2432. !EvalResult.hasSideEffects())
  2433. Value = &EvalResult.Val;
  2434. llvm::Constant *InitialValue = nullptr;
  2435. bool Constant = false;
  2436. llvm::Type *Type;
  2437. if (Value) {
  2438. // The temporary has a constant initializer, use it.
  2439. InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
  2440. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  2441. Type = InitialValue->getType();
  2442. } else {
  2443. // No initializer, the initialization will be provided when we
  2444. // initialize the declaration which performed lifetime extension.
  2445. Type = getTypes().ConvertTypeForMem(MaterializedType);
  2446. }
  2447. // Create a global variable for this lifetime-extended temporary.
  2448. llvm::GlobalValue::LinkageTypes Linkage =
  2449. getLLVMLinkageVarDefinition(VD, Constant);
  2450. // There is no need for this temporary to have global linkage if the global
  2451. // variable has external linkage.
  2452. if (Linkage == llvm::GlobalVariable::ExternalLinkage)
  2453. Linkage = llvm::GlobalVariable::PrivateLinkage;
  2454. unsigned AddrSpace = GetGlobalVarAddressSpace(
  2455. VD, getContext().getTargetAddressSpace(MaterializedType));
  2456. auto *GV = new llvm::GlobalVariable(
  2457. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  2458. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
  2459. AddrSpace);
  2460. setGlobalVisibility(GV, VD);
  2461. GV->setAlignment(
  2462. getContext().getTypeAlignInChars(MaterializedType).getQuantity());
  2463. if (VD->getTLSKind())
  2464. setTLSMode(GV, *VD);
  2465. Slot = GV;
  2466. return GV;
  2467. }
  2468. /// EmitObjCPropertyImplementations - Emit information for synthesized
  2469. /// properties for an implementation.
  2470. void CodeGenModule::EmitObjCPropertyImplementations(const
  2471. ObjCImplementationDecl *D) {
  2472. for (const auto *PID : D->property_impls()) {
  2473. // Dynamic is just for type-checking.
  2474. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  2475. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  2476. // Determine which methods need to be implemented, some may have
  2477. // been overridden. Note that ::isPropertyAccessor is not the method
  2478. // we want, that just indicates if the decl came from a
  2479. // property. What we want to know is if the method is defined in
  2480. // this implementation.
  2481. if (!D->getInstanceMethod(PD->getGetterName()))
  2482. CodeGenFunction(*this).GenerateObjCGetter(
  2483. const_cast<ObjCImplementationDecl *>(D), PID);
  2484. if (!PD->isReadOnly() &&
  2485. !D->getInstanceMethod(PD->getSetterName()))
  2486. CodeGenFunction(*this).GenerateObjCSetter(
  2487. const_cast<ObjCImplementationDecl *>(D), PID);
  2488. }
  2489. }
  2490. }
  2491. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  2492. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  2493. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  2494. ivar; ivar = ivar->getNextIvar())
  2495. if (ivar->getType().isDestructedType())
  2496. return true;
  2497. return false;
  2498. }
  2499. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  2500. /// for an implementation.
  2501. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  2502. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  2503. if (needsDestructMethod(D)) {
  2504. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  2505. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2506. ObjCMethodDecl *DTORMethod =
  2507. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  2508. cxxSelector, getContext().VoidTy, nullptr, D,
  2509. /*isInstance=*/true, /*isVariadic=*/false,
  2510. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  2511. /*isDefined=*/false, ObjCMethodDecl::Required);
  2512. D->addInstanceMethod(DTORMethod);
  2513. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  2514. D->setHasDestructors(true);
  2515. }
  2516. // If the implementation doesn't have any ivar initializers, we don't need
  2517. // a .cxx_construct.
  2518. if (D->getNumIvarInitializers() == 0)
  2519. return;
  2520. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  2521. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  2522. // The constructor returns 'self'.
  2523. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  2524. D->getLocation(),
  2525. D->getLocation(),
  2526. cxxSelector,
  2527. getContext().getObjCIdType(),
  2528. nullptr, D, /*isInstance=*/true,
  2529. /*isVariadic=*/false,
  2530. /*isPropertyAccessor=*/true,
  2531. /*isImplicitlyDeclared=*/true,
  2532. /*isDefined=*/false,
  2533. ObjCMethodDecl::Required);
  2534. D->addInstanceMethod(CTORMethod);
  2535. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  2536. D->setHasNonZeroConstructors(true);
  2537. }
  2538. /// EmitNamespace - Emit all declarations in a namespace.
  2539. void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
  2540. for (auto *I : ND->decls()) {
  2541. if (const auto *VD = dyn_cast<VarDecl>(I))
  2542. if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
  2543. VD->getTemplateSpecializationKind() != TSK_Undeclared)
  2544. continue;
  2545. EmitTopLevelDecl(I);
  2546. }
  2547. }
  2548. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  2549. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  2550. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  2551. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  2552. ErrorUnsupported(LSD, "linkage spec");
  2553. return;
  2554. }
  2555. for (auto *I : LSD->decls()) {
  2556. // Meta-data for ObjC class includes references to implemented methods.
  2557. // Generate class's method definitions first.
  2558. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  2559. for (auto *M : OID->methods())
  2560. EmitTopLevelDecl(M);
  2561. }
  2562. EmitTopLevelDecl(I);
  2563. }
  2564. }
  2565. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  2566. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  2567. // Ignore dependent declarations.
  2568. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  2569. return;
  2570. switch (D->getKind()) {
  2571. case Decl::CXXConversion:
  2572. case Decl::CXXMethod:
  2573. case Decl::Function:
  2574. // Skip function templates
  2575. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2576. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2577. return;
  2578. EmitGlobal(cast<FunctionDecl>(D));
  2579. // Always provide some coverage mapping
  2580. // even for the functions that aren't emitted.
  2581. AddDeferredUnusedCoverageMapping(D);
  2582. break;
  2583. case Decl::Var:
  2584. // Skip variable templates
  2585. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  2586. return;
  2587. case Decl::VarTemplateSpecialization:
  2588. EmitGlobal(cast<VarDecl>(D));
  2589. break;
  2590. // Indirect fields from global anonymous structs and unions can be
  2591. // ignored; only the actual variable requires IR gen support.
  2592. case Decl::IndirectField:
  2593. break;
  2594. // C++ Decls
  2595. case Decl::Namespace:
  2596. EmitNamespace(cast<NamespaceDecl>(D));
  2597. break;
  2598. // No code generation needed.
  2599. case Decl::UsingShadow:
  2600. case Decl::ClassTemplate:
  2601. case Decl::VarTemplate:
  2602. case Decl::VarTemplatePartialSpecialization:
  2603. case Decl::FunctionTemplate:
  2604. case Decl::TypeAliasTemplate:
  2605. case Decl::Block:
  2606. case Decl::Empty:
  2607. break;
  2608. case Decl::Using: // using X; [C++]
  2609. if (CGDebugInfo *DI = getModuleDebugInfo())
  2610. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  2611. return;
  2612. case Decl::NamespaceAlias:
  2613. if (CGDebugInfo *DI = getModuleDebugInfo())
  2614. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  2615. return;
  2616. case Decl::UsingDirective: // using namespace X; [C++]
  2617. if (CGDebugInfo *DI = getModuleDebugInfo())
  2618. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  2619. return;
  2620. case Decl::CXXConstructor:
  2621. // Skip function templates
  2622. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  2623. cast<FunctionDecl>(D)->isLateTemplateParsed())
  2624. return;
  2625. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  2626. break;
  2627. case Decl::CXXDestructor:
  2628. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  2629. return;
  2630. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  2631. break;
  2632. case Decl::StaticAssert:
  2633. // Nothing to do.
  2634. break;
  2635. // Objective-C Decls
  2636. // Forward declarations, no (immediate) code generation.
  2637. case Decl::ObjCInterface:
  2638. case Decl::ObjCCategory:
  2639. break;
  2640. case Decl::ObjCProtocol: {
  2641. auto *Proto = cast<ObjCProtocolDecl>(D);
  2642. if (Proto->isThisDeclarationADefinition())
  2643. ObjCRuntime->GenerateProtocol(Proto);
  2644. break;
  2645. }
  2646. case Decl::ObjCCategoryImpl:
  2647. // Categories have properties but don't support synthesize so we
  2648. // can ignore them here.
  2649. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  2650. break;
  2651. case Decl::ObjCImplementation: {
  2652. auto *OMD = cast<ObjCImplementationDecl>(D);
  2653. EmitObjCPropertyImplementations(OMD);
  2654. EmitObjCIvarInitializations(OMD);
  2655. ObjCRuntime->GenerateClass(OMD);
  2656. // Emit global variable debug information.
  2657. if (CGDebugInfo *DI = getModuleDebugInfo())
  2658. if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  2659. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  2660. OMD->getClassInterface()), OMD->getLocation());
  2661. break;
  2662. }
  2663. case Decl::ObjCMethod: {
  2664. auto *OMD = cast<ObjCMethodDecl>(D);
  2665. // If this is not a prototype, emit the body.
  2666. if (OMD->getBody())
  2667. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  2668. break;
  2669. }
  2670. case Decl::ObjCCompatibleAlias:
  2671. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  2672. break;
  2673. case Decl::LinkageSpec:
  2674. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  2675. break;
  2676. case Decl::FileScopeAsm: {
  2677. auto *AD = cast<FileScopeAsmDecl>(D);
  2678. StringRef AsmString = AD->getAsmString()->getString();
  2679. const std::string &S = getModule().getModuleInlineAsm();
  2680. if (S.empty())
  2681. getModule().setModuleInlineAsm(AsmString);
  2682. else if (S.end()[-1] == '\n')
  2683. getModule().setModuleInlineAsm(S + AsmString.str());
  2684. else
  2685. getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
  2686. break;
  2687. }
  2688. case Decl::Import: {
  2689. auto *Import = cast<ImportDecl>(D);
  2690. // Ignore import declarations that come from imported modules.
  2691. if (clang::Module *Owner = Import->getOwningModule()) {
  2692. if (getLangOpts().CurrentModule.empty() ||
  2693. Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
  2694. break;
  2695. }
  2696. ImportedModules.insert(Import->getImportedModule());
  2697. break;
  2698. }
  2699. case Decl::ClassTemplateSpecialization: {
  2700. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  2701. if (DebugInfo &&
  2702. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
  2703. DebugInfo->completeTemplateDefinition(*Spec);
  2704. }
  2705. default:
  2706. // Make sure we handled everything we should, every other kind is a
  2707. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  2708. // function. Need to recode Decl::Kind to do that easily.
  2709. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  2710. }
  2711. }
  2712. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  2713. // Do we need to generate coverage mapping?
  2714. if (!CodeGenOpts.CoverageMapping)
  2715. return;
  2716. switch (D->getKind()) {
  2717. case Decl::CXXConversion:
  2718. case Decl::CXXMethod:
  2719. case Decl::Function:
  2720. case Decl::ObjCMethod:
  2721. case Decl::CXXConstructor:
  2722. case Decl::CXXDestructor: {
  2723. if (!cast<FunctionDecl>(D)->hasBody())
  2724. return;
  2725. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  2726. if (I == DeferredEmptyCoverageMappingDecls.end())
  2727. DeferredEmptyCoverageMappingDecls[D] = true;
  2728. break;
  2729. }
  2730. default:
  2731. break;
  2732. };
  2733. }
  2734. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  2735. // Do we need to generate coverage mapping?
  2736. if (!CodeGenOpts.CoverageMapping)
  2737. return;
  2738. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  2739. if (Fn->isTemplateInstantiation())
  2740. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  2741. }
  2742. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  2743. if (I == DeferredEmptyCoverageMappingDecls.end())
  2744. DeferredEmptyCoverageMappingDecls[D] = false;
  2745. else
  2746. I->second = false;
  2747. }
  2748. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  2749. std::vector<const Decl *> DeferredDecls;
  2750. for (const auto I : DeferredEmptyCoverageMappingDecls) {
  2751. if (!I.second)
  2752. continue;
  2753. DeferredDecls.push_back(I.first);
  2754. }
  2755. // Sort the declarations by their location to make sure that the tests get a
  2756. // predictable order for the coverage mapping for the unused declarations.
  2757. if (CodeGenOpts.DumpCoverageMapping)
  2758. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  2759. [] (const Decl *LHS, const Decl *RHS) {
  2760. return LHS->getLocStart() < RHS->getLocStart();
  2761. });
  2762. for (const auto *D : DeferredDecls) {
  2763. switch (D->getKind()) {
  2764. case Decl::CXXConversion:
  2765. case Decl::CXXMethod:
  2766. case Decl::Function:
  2767. case Decl::ObjCMethod: {
  2768. CodeGenPGO PGO(*this);
  2769. GlobalDecl GD(cast<FunctionDecl>(D));
  2770. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  2771. getFunctionLinkage(GD));
  2772. break;
  2773. }
  2774. case Decl::CXXConstructor: {
  2775. CodeGenPGO PGO(*this);
  2776. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  2777. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  2778. getFunctionLinkage(GD));
  2779. break;
  2780. }
  2781. case Decl::CXXDestructor: {
  2782. CodeGenPGO PGO(*this);
  2783. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  2784. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  2785. getFunctionLinkage(GD));
  2786. break;
  2787. }
  2788. default:
  2789. break;
  2790. };
  2791. }
  2792. }
  2793. /// Turns the given pointer into a constant.
  2794. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  2795. const void *Ptr) {
  2796. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  2797. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  2798. return llvm::ConstantInt::get(i64, PtrInt);
  2799. }
  2800. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  2801. llvm::NamedMDNode *&GlobalMetadata,
  2802. GlobalDecl D,
  2803. llvm::GlobalValue *Addr) {
  2804. if (!GlobalMetadata)
  2805. GlobalMetadata =
  2806. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  2807. // TODO: should we report variant information for ctors/dtors?
  2808. llvm::Value *Ops[] = {
  2809. Addr,
  2810. GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
  2811. };
  2812. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2813. }
  2814. /// For each function which is declared within an extern "C" region and marked
  2815. /// as 'used', but has internal linkage, create an alias from the unmangled
  2816. /// name to the mangled name if possible. People expect to be able to refer
  2817. /// to such functions with an unmangled name from inline assembly within the
  2818. /// same translation unit.
  2819. void CodeGenModule::EmitStaticExternCAliases() {
  2820. for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
  2821. E = StaticExternCValues.end();
  2822. I != E; ++I) {
  2823. IdentifierInfo *Name = I->first;
  2824. llvm::GlobalValue *Val = I->second;
  2825. if (Val && !getModule().getNamedValue(Name->getName()))
  2826. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  2827. }
  2828. }
  2829. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  2830. GlobalDecl &Result) const {
  2831. auto Res = Manglings.find(MangledName);
  2832. if (Res == Manglings.end())
  2833. return false;
  2834. Result = Res->getValue();
  2835. return true;
  2836. }
  2837. /// Emits metadata nodes associating all the global values in the
  2838. /// current module with the Decls they came from. This is useful for
  2839. /// projects using IR gen as a subroutine.
  2840. ///
  2841. /// Since there's currently no way to associate an MDNode directly
  2842. /// with an llvm::GlobalValue, we create a global named metadata
  2843. /// with the name 'clang.global.decl.ptrs'.
  2844. void CodeGenModule::EmitDeclMetadata() {
  2845. llvm::NamedMDNode *GlobalMetadata = nullptr;
  2846. // StaticLocalDeclMap
  2847. for (auto &I : MangledDeclNames) {
  2848. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  2849. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  2850. }
  2851. }
  2852. /// Emits metadata nodes for all the local variables in the current
  2853. /// function.
  2854. void CodeGenFunction::EmitDeclMetadata() {
  2855. if (LocalDeclMap.empty()) return;
  2856. llvm::LLVMContext &Context = getLLVMContext();
  2857. // Find the unique metadata ID for this name.
  2858. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  2859. llvm::NamedMDNode *GlobalMetadata = nullptr;
  2860. for (auto &I : LocalDeclMap) {
  2861. const Decl *D = I.first;
  2862. llvm::Value *Addr = I.second;
  2863. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  2864. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  2865. Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
  2866. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  2867. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  2868. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  2869. }
  2870. }
  2871. }
  2872. void CodeGenModule::EmitVersionIdentMetadata() {
  2873. llvm::NamedMDNode *IdentMetadata =
  2874. TheModule.getOrInsertNamedMetadata("llvm.ident");
  2875. std::string Version = getClangFullVersion();
  2876. llvm::LLVMContext &Ctx = TheModule.getContext();
  2877. llvm::Value *IdentNode[] = {
  2878. llvm::MDString::get(Ctx, Version)
  2879. };
  2880. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  2881. }
  2882. void CodeGenModule::EmitTargetMetadata() {
  2883. // Warning, new MangledDeclNames may be appended within this loop.
  2884. // We rely on MapVector insertions adding new elements to the end
  2885. // of the container.
  2886. // FIXME: Move this loop into the one target that needs it, and only
  2887. // loop over those declarations for which we couldn't emit the target
  2888. // metadata when we emitted the declaration.
  2889. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  2890. auto Val = *(MangledDeclNames.begin() + I);
  2891. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  2892. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  2893. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  2894. }
  2895. }
  2896. void CodeGenModule::EmitCoverageFile() {
  2897. if (!getCodeGenOpts().CoverageFile.empty()) {
  2898. if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
  2899. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  2900. llvm::LLVMContext &Ctx = TheModule.getContext();
  2901. llvm::MDString *CoverageFile =
  2902. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
  2903. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  2904. llvm::MDNode *CU = CUNode->getOperand(i);
  2905. llvm::Value *node[] = { CoverageFile, CU };
  2906. llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
  2907. GCov->addOperand(N);
  2908. }
  2909. }
  2910. }
  2911. }
  2912. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
  2913. QualType GuidType) {
  2914. // Sema has checked that all uuid strings are of the form
  2915. // "12345678-1234-1234-1234-1234567890ab".
  2916. assert(Uuid.size() == 36);
  2917. for (unsigned i = 0; i < 36; ++i) {
  2918. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  2919. else assert(isHexDigit(Uuid[i]));
  2920. }
  2921. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  2922. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  2923. llvm::Constant *Field3[8];
  2924. for (unsigned Idx = 0; Idx < 8; ++Idx)
  2925. Field3[Idx] = llvm::ConstantInt::get(
  2926. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  2927. llvm::Constant *Fields[4] = {
  2928. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  2929. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  2930. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  2931. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  2932. };
  2933. return llvm::ConstantStruct::getAnon(Fields);
  2934. }
  2935. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  2936. bool ForEH) {
  2937. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  2938. // FIXME: should we even be calling this method if RTTI is disabled
  2939. // and it's not for EH?
  2940. if (!ForEH && !getLangOpts().RTTI)
  2941. return llvm::Constant::getNullValue(Int8PtrTy);
  2942. if (ForEH && Ty->isObjCObjectPointerType() &&
  2943. LangOpts.ObjCRuntime.isGNUFamily())
  2944. return ObjCRuntime->GetEHType(Ty);
  2945. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  2946. }