CodeGenModule.cpp 158 KB

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