CodeGenFunction.cpp 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the per-function state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenFunction.h"
  13. #include "CGBlocks.h"
  14. #include "CGCleanup.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/ASTContext.h"
  23. #include "clang/AST/ASTLambda.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/StmtObjC.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/CodeGenOptions.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/CodeGen/CGFunctionInfo.h"
  32. #include "clang/Frontend/FrontendDiagnostic.h"
  33. #include "llvm/IR/DataLayout.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  39. using namespace clang;
  40. using namespace CodeGen;
  41. /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
  42. /// markers.
  43. static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
  44. const LangOptions &LangOpts) {
  45. if (CGOpts.DisableLifetimeMarkers)
  46. return false;
  47. // Disable lifetime markers in msan builds.
  48. // FIXME: Remove this when msan works with lifetime markers.
  49. if (LangOpts.Sanitize.has(SanitizerKind::Memory))
  50. return false;
  51. // Asan uses markers for use-after-scope checks.
  52. if (CGOpts.SanitizeAddressUseAfterScope)
  53. return true;
  54. // For now, only in optimized builds.
  55. return CGOpts.OptimizationLevel != 0;
  56. }
  57. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  58. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  59. Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(),
  60. CGBuilderInserterTy(this)),
  61. SanOpts(CGM.getLangOpts().Sanitize), DebugInfo(CGM.getModuleDebugInfo()),
  62. PGO(cgm), ShouldEmitLifetimeMarkers(shouldEmitLifetimeMarkers(
  63. CGM.getCodeGenOpts(), CGM.getLangOpts())) {
  64. if (!suppressNewContext)
  65. CGM.getCXXABI().getMangleContext().startNewFunction();
  66. llvm::FastMathFlags FMF;
  67. if (CGM.getLangOpts().FastMath)
  68. FMF.setFast();
  69. if (CGM.getLangOpts().FiniteMathOnly) {
  70. FMF.setNoNaNs();
  71. FMF.setNoInfs();
  72. }
  73. if (CGM.getCodeGenOpts().NoNaNsFPMath) {
  74. FMF.setNoNaNs();
  75. }
  76. if (CGM.getCodeGenOpts().NoSignedZeros) {
  77. FMF.setNoSignedZeros();
  78. }
  79. if (CGM.getCodeGenOpts().ReciprocalMath) {
  80. FMF.setAllowReciprocal();
  81. }
  82. if (CGM.getCodeGenOpts().Reassociate) {
  83. FMF.setAllowReassoc();
  84. }
  85. Builder.setFastMathFlags(FMF);
  86. }
  87. CodeGenFunction::~CodeGenFunction() {
  88. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  89. // If there are any unclaimed block infos, go ahead and destroy them
  90. // now. This can happen if IR-gen gets clever and skips evaluating
  91. // something.
  92. if (FirstBlockInfo)
  93. destroyBlockInfos(FirstBlockInfo);
  94. if (getLangOpts().OpenMP && CurFn)
  95. CGM.getOpenMPRuntime().functionFinished(*this);
  96. }
  97. CharUnits CodeGenFunction::getNaturalPointeeTypeAlignment(QualType T,
  98. LValueBaseInfo *BaseInfo,
  99. TBAAAccessInfo *TBAAInfo) {
  100. return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
  101. /* forPointeeType= */ true);
  102. }
  103. CharUnits CodeGenFunction::getNaturalTypeAlignment(QualType T,
  104. LValueBaseInfo *BaseInfo,
  105. TBAAAccessInfo *TBAAInfo,
  106. bool forPointeeType) {
  107. if (TBAAInfo)
  108. *TBAAInfo = CGM.getTBAAAccessInfo(T);
  109. // Honor alignment typedef attributes even on incomplete types.
  110. // We also honor them straight for C++ class types, even as pointees;
  111. // there's an expressivity gap here.
  112. if (auto TT = T->getAs<TypedefType>()) {
  113. if (auto Align = TT->getDecl()->getMaxAlignment()) {
  114. if (BaseInfo)
  115. *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
  116. return getContext().toCharUnitsFromBits(Align);
  117. }
  118. }
  119. if (BaseInfo)
  120. *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
  121. CharUnits Alignment;
  122. if (T->isIncompleteType()) {
  123. Alignment = CharUnits::One(); // Shouldn't be used, but pessimistic is best.
  124. } else {
  125. // For C++ class pointees, we don't know whether we're pointing at a
  126. // base or a complete object, so we generally need to use the
  127. // non-virtual alignment.
  128. const CXXRecordDecl *RD;
  129. if (forPointeeType && (RD = T->getAsCXXRecordDecl())) {
  130. Alignment = CGM.getClassPointerAlignment(RD);
  131. } else {
  132. Alignment = getContext().getTypeAlignInChars(T);
  133. if (T.getQualifiers().hasUnaligned())
  134. Alignment = CharUnits::One();
  135. }
  136. // Cap to the global maximum type alignment unless the alignment
  137. // was somehow explicit on the type.
  138. if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
  139. if (Alignment.getQuantity() > MaxAlign &&
  140. !getContext().isAlignmentRequired(T))
  141. Alignment = CharUnits::fromQuantity(MaxAlign);
  142. }
  143. }
  144. return Alignment;
  145. }
  146. LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  147. LValueBaseInfo BaseInfo;
  148. TBAAAccessInfo TBAAInfo;
  149. CharUnits Alignment = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo);
  150. return LValue::MakeAddr(Address(V, Alignment), T, getContext(), BaseInfo,
  151. TBAAInfo);
  152. }
  153. /// Given a value of type T* that may not be to a complete object,
  154. /// construct an l-value with the natural pointee alignment of T.
  155. LValue
  156. CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) {
  157. LValueBaseInfo BaseInfo;
  158. TBAAAccessInfo TBAAInfo;
  159. CharUnits Align = getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo,
  160. /* forPointeeType= */ true);
  161. return MakeAddrLValue(Address(V, Align), T, BaseInfo, TBAAInfo);
  162. }
  163. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  164. return CGM.getTypes().ConvertTypeForMem(T);
  165. }
  166. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  167. return CGM.getTypes().ConvertType(T);
  168. }
  169. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  170. type = type.getCanonicalType();
  171. while (true) {
  172. switch (type->getTypeClass()) {
  173. #define TYPE(name, parent)
  174. #define ABSTRACT_TYPE(name, parent)
  175. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  176. #define DEPENDENT_TYPE(name, parent) case Type::name:
  177. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  178. #include "clang/AST/TypeNodes.def"
  179. llvm_unreachable("non-canonical or dependent type in IR-generation");
  180. case Type::Auto:
  181. case Type::DeducedTemplateSpecialization:
  182. llvm_unreachable("undeduced type in IR-generation");
  183. // Various scalar types.
  184. case Type::Builtin:
  185. case Type::Pointer:
  186. case Type::BlockPointer:
  187. case Type::LValueReference:
  188. case Type::RValueReference:
  189. case Type::MemberPointer:
  190. case Type::Vector:
  191. case Type::ExtVector:
  192. case Type::FunctionProto:
  193. case Type::FunctionNoProto:
  194. case Type::Enum:
  195. case Type::ObjCObjectPointer:
  196. case Type::Pipe:
  197. return TEK_Scalar;
  198. // Complexes.
  199. case Type::Complex:
  200. return TEK_Complex;
  201. // Arrays, records, and Objective-C objects.
  202. case Type::ConstantArray:
  203. case Type::IncompleteArray:
  204. case Type::VariableArray:
  205. case Type::Record:
  206. case Type::ObjCObject:
  207. case Type::ObjCInterface:
  208. return TEK_Aggregate;
  209. // We operate on atomic values according to their underlying type.
  210. case Type::Atomic:
  211. type = cast<AtomicType>(type)->getValueType();
  212. continue;
  213. }
  214. llvm_unreachable("unknown type kind!");
  215. }
  216. }
  217. llvm::DebugLoc CodeGenFunction::EmitReturnBlock() {
  218. // For cleanliness, we try to avoid emitting the return block for
  219. // simple cases.
  220. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  221. if (CurBB) {
  222. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  223. // We have a valid insert point, reuse it if it is empty or there are no
  224. // explicit jumps to the return block.
  225. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  226. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  227. delete ReturnBlock.getBlock();
  228. } else
  229. EmitBlock(ReturnBlock.getBlock());
  230. return llvm::DebugLoc();
  231. }
  232. // Otherwise, if the return block is the target of a single direct
  233. // branch then we can just put the code in that block instead. This
  234. // cleans up functions which started with a unified return block.
  235. if (ReturnBlock.getBlock()->hasOneUse()) {
  236. llvm::BranchInst *BI =
  237. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin());
  238. if (BI && BI->isUnconditional() &&
  239. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  240. // Record/return the DebugLoc of the simple 'return' expression to be used
  241. // later by the actual 'ret' instruction.
  242. llvm::DebugLoc Loc = BI->getDebugLoc();
  243. Builder.SetInsertPoint(BI->getParent());
  244. BI->eraseFromParent();
  245. delete ReturnBlock.getBlock();
  246. return Loc;
  247. }
  248. }
  249. // FIXME: We are at an unreachable point, there is no reason to emit the block
  250. // unless it has uses. However, we still need a place to put the debug
  251. // region.end for now.
  252. EmitBlock(ReturnBlock.getBlock());
  253. return llvm::DebugLoc();
  254. }
  255. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  256. if (!BB) return;
  257. if (!BB->use_empty())
  258. return CGF.CurFn->getBasicBlockList().push_back(BB);
  259. delete BB;
  260. }
  261. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  262. assert(BreakContinueStack.empty() &&
  263. "mismatched push/pop in break/continue stack!");
  264. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  265. && NumSimpleReturnExprs == NumReturnExprs
  266. && ReturnBlock.getBlock()->use_empty();
  267. // Usually the return expression is evaluated before the cleanup
  268. // code. If the function contains only a simple return statement,
  269. // such as a constant, the location before the cleanup code becomes
  270. // the last useful breakpoint in the function, because the simple
  271. // return expression will be evaluated after the cleanup code. To be
  272. // safe, set the debug location for cleanup code to the location of
  273. // the return statement. Otherwise the cleanup code should be at the
  274. // end of the function's lexical scope.
  275. //
  276. // If there are multiple branches to the return block, the branch
  277. // instructions will get the location of the return statements and
  278. // all will be fine.
  279. if (CGDebugInfo *DI = getDebugInfo()) {
  280. if (OnlySimpleReturnStmts)
  281. DI->EmitLocation(Builder, LastStopPoint);
  282. else
  283. DI->EmitLocation(Builder, EndLoc);
  284. }
  285. // Pop any cleanups that might have been associated with the
  286. // parameters. Do this in whatever block we're currently in; it's
  287. // important to do this before we enter the return block or return
  288. // edges will be *really* confused.
  289. bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth;
  290. bool HasOnlyLifetimeMarkers =
  291. HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth);
  292. bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
  293. if (HasCleanups) {
  294. // Make sure the line table doesn't jump back into the body for
  295. // the ret after it's been at EndLoc.
  296. if (CGDebugInfo *DI = getDebugInfo())
  297. if (OnlySimpleReturnStmts)
  298. DI->EmitLocation(Builder, EndLoc);
  299. PopCleanupBlocks(PrologueCleanupDepth);
  300. }
  301. // Emit function epilog (to return).
  302. llvm::DebugLoc Loc = EmitReturnBlock();
  303. if (ShouldInstrumentFunction()) {
  304. if (CGM.getCodeGenOpts().InstrumentFunctions)
  305. CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit");
  306. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  307. CurFn->addFnAttr("instrument-function-exit-inlined",
  308. "__cyg_profile_func_exit");
  309. }
  310. // Emit debug descriptor for function end.
  311. if (CGDebugInfo *DI = getDebugInfo())
  312. DI->EmitFunctionEnd(Builder, CurFn);
  313. // Reset the debug location to that of the simple 'return' expression, if any
  314. // rather than that of the end of the function's scope '}'.
  315. ApplyDebugLocation AL(*this, Loc);
  316. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  317. EmitEndEHSpec(CurCodeDecl);
  318. assert(EHStack.empty() &&
  319. "did not remove all scopes from cleanup stack!");
  320. // If someone did an indirect goto, emit the indirect goto block at the end of
  321. // the function.
  322. if (IndirectBranch) {
  323. EmitBlock(IndirectBranch->getParent());
  324. Builder.ClearInsertionPoint();
  325. }
  326. // If some of our locals escaped, insert a call to llvm.localescape in the
  327. // entry block.
  328. if (!EscapedLocals.empty()) {
  329. // Invert the map from local to index into a simple vector. There should be
  330. // no holes.
  331. SmallVector<llvm::Value *, 4> EscapeArgs;
  332. EscapeArgs.resize(EscapedLocals.size());
  333. for (auto &Pair : EscapedLocals)
  334. EscapeArgs[Pair.second] = Pair.first;
  335. llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration(
  336. &CGM.getModule(), llvm::Intrinsic::localescape);
  337. CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs);
  338. }
  339. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  340. llvm::Instruction *Ptr = AllocaInsertPt;
  341. AllocaInsertPt = nullptr;
  342. Ptr->eraseFromParent();
  343. // If someone took the address of a label but never did an indirect goto, we
  344. // made a zero entry PHI node, which is illegal, zap it now.
  345. if (IndirectBranch) {
  346. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  347. if (PN->getNumIncomingValues() == 0) {
  348. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  349. PN->eraseFromParent();
  350. }
  351. }
  352. EmitIfUsed(*this, EHResumeBlock);
  353. EmitIfUsed(*this, TerminateLandingPad);
  354. EmitIfUsed(*this, TerminateHandler);
  355. EmitIfUsed(*this, UnreachableBlock);
  356. for (const auto &FuncletAndParent : TerminateFunclets)
  357. EmitIfUsed(*this, FuncletAndParent.second);
  358. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  359. EmitDeclMetadata();
  360. for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator
  361. I = DeferredReplacements.begin(),
  362. E = DeferredReplacements.end();
  363. I != E; ++I) {
  364. I->first->replaceAllUsesWith(I->second);
  365. I->first->eraseFromParent();
  366. }
  367. // Eliminate CleanupDestSlot alloca by replacing it with SSA values and
  368. // PHIs if the current function is a coroutine. We don't do it for all
  369. // functions as it may result in slight increase in numbers of instructions
  370. // if compiled with no optimizations. We do it for coroutine as the lifetime
  371. // of CleanupDestSlot alloca make correct coroutine frame building very
  372. // difficult.
  373. if (NormalCleanupDest.isValid() && isCoroutine()) {
  374. llvm::DominatorTree DT(*CurFn);
  375. llvm::PromoteMemToReg(
  376. cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT);
  377. NormalCleanupDest = Address::invalid();
  378. }
  379. // Scan function arguments for vector width.
  380. for (llvm::Argument &A : CurFn->args())
  381. if (auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
  382. LargestVectorWidth = std::max(LargestVectorWidth,
  383. VT->getPrimitiveSizeInBits());
  384. // Update vector width based on return type.
  385. if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType()))
  386. LargestVectorWidth = std::max(LargestVectorWidth,
  387. VT->getPrimitiveSizeInBits());
  388. // Add the required-vector-width attribute. This contains the max width from:
  389. // 1. min-vector-width attribute used in the source program.
  390. // 2. Any builtins used that have a vector width specified.
  391. // 3. Values passed in and out of inline assembly.
  392. // 4. Width of vector arguments and return types for this function.
  393. // 5. Width of vector aguments and return types for functions called by this
  394. // function.
  395. CurFn->addFnAttr("min-legal-vector-width", llvm::utostr(LargestVectorWidth));
  396. }
  397. /// ShouldInstrumentFunction - Return true if the current function should be
  398. /// instrumented with __cyg_profile_func_* calls
  399. bool CodeGenFunction::ShouldInstrumentFunction() {
  400. if (!CGM.getCodeGenOpts().InstrumentFunctions &&
  401. !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining &&
  402. !CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  403. return false;
  404. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  405. return false;
  406. return true;
  407. }
  408. /// ShouldXRayInstrument - Return true if the current function should be
  409. /// instrumented with XRay nop sleds.
  410. bool CodeGenFunction::ShouldXRayInstrumentFunction() const {
  411. return CGM.getCodeGenOpts().XRayInstrumentFunctions;
  412. }
  413. /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to
  414. /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation.
  415. bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const {
  416. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  417. (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents ||
  418. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  419. XRayInstrKind::Custom);
  420. }
  421. bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const {
  422. return CGM.getCodeGenOpts().XRayInstrumentFunctions &&
  423. (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents ||
  424. CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask ==
  425. XRayInstrKind::Typed);
  426. }
  427. llvm::Constant *
  428. CodeGenFunction::EncodeAddrForUseInPrologue(llvm::Function *F,
  429. llvm::Constant *Addr) {
  430. // Addresses stored in prologue data can't require run-time fixups and must
  431. // be PC-relative. Run-time fixups are undesirable because they necessitate
  432. // writable text segments, which are unsafe. And absolute addresses are
  433. // undesirable because they break PIE mode.
  434. // Add a layer of indirection through a private global. Taking its address
  435. // won't result in a run-time fixup, even if Addr has linkonce_odr linkage.
  436. auto *GV = new llvm::GlobalVariable(CGM.getModule(), Addr->getType(),
  437. /*isConstant=*/true,
  438. llvm::GlobalValue::PrivateLinkage, Addr);
  439. // Create a PC-relative address.
  440. auto *GOTAsInt = llvm::ConstantExpr::getPtrToInt(GV, IntPtrTy);
  441. auto *FuncAsInt = llvm::ConstantExpr::getPtrToInt(F, IntPtrTy);
  442. auto *PCRelAsInt = llvm::ConstantExpr::getSub(GOTAsInt, FuncAsInt);
  443. return (IntPtrTy == Int32Ty)
  444. ? PCRelAsInt
  445. : llvm::ConstantExpr::getTrunc(PCRelAsInt, Int32Ty);
  446. }
  447. llvm::Value *
  448. CodeGenFunction::DecodeAddrUsedInPrologue(llvm::Value *F,
  449. llvm::Value *EncodedAddr) {
  450. // Reconstruct the address of the global.
  451. auto *PCRelAsInt = Builder.CreateSExt(EncodedAddr, IntPtrTy);
  452. auto *FuncAsInt = Builder.CreatePtrToInt(F, IntPtrTy, "func_addr.int");
  453. auto *GOTAsInt = Builder.CreateAdd(PCRelAsInt, FuncAsInt, "global_addr.int");
  454. auto *GOTAddr = Builder.CreateIntToPtr(GOTAsInt, Int8PtrPtrTy, "global_addr");
  455. // Load the original pointer through the global.
  456. return Builder.CreateLoad(Address(GOTAddr, getPointerAlign()),
  457. "decoded_addr");
  458. }
  459. static void removeImageAccessQualifier(std::string& TyName) {
  460. std::string ReadOnlyQual("__read_only");
  461. std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
  462. if (ReadOnlyPos != std::string::npos)
  463. // "+ 1" for the space after access qualifier.
  464. TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
  465. else {
  466. std::string WriteOnlyQual("__write_only");
  467. std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
  468. if (WriteOnlyPos != std::string::npos)
  469. TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
  470. else {
  471. std::string ReadWriteQual("__read_write");
  472. std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
  473. if (ReadWritePos != std::string::npos)
  474. TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
  475. }
  476. }
  477. }
  478. // Returns the address space id that should be produced to the
  479. // kernel_arg_addr_space metadata. This is always fixed to the ids
  480. // as specified in the SPIR 2.0 specification in order to differentiate
  481. // for example in clGetKernelArgInfo() implementation between the address
  482. // spaces with targets without unique mapping to the OpenCL address spaces
  483. // (basically all single AS CPUs).
  484. static unsigned ArgInfoAddressSpace(LangAS AS) {
  485. switch (AS) {
  486. case LangAS::opencl_global: return 1;
  487. case LangAS::opencl_constant: return 2;
  488. case LangAS::opencl_local: return 3;
  489. case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
  490. default:
  491. return 0; // Assume private.
  492. }
  493. }
  494. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  495. // information in the program executable. The argument information stored
  496. // includes the argument name, its type, the address and access qualifiers used.
  497. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  498. CodeGenModule &CGM, llvm::LLVMContext &Context,
  499. CGBuilderTy &Builder, ASTContext &ASTCtx) {
  500. // Create MDNodes that represent the kernel arg metadata.
  501. // Each MDNode is a list in the form of "key", N number of values which is
  502. // the same number of values as their are kernel arguments.
  503. const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy();
  504. // MDNode for the kernel argument address space qualifiers.
  505. SmallVector<llvm::Metadata *, 8> addressQuals;
  506. // MDNode for the kernel argument access qualifiers (images only).
  507. SmallVector<llvm::Metadata *, 8> accessQuals;
  508. // MDNode for the kernel argument type names.
  509. SmallVector<llvm::Metadata *, 8> argTypeNames;
  510. // MDNode for the kernel argument base type names.
  511. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  512. // MDNode for the kernel argument type qualifiers.
  513. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  514. // MDNode for the kernel argument names.
  515. SmallVector<llvm::Metadata *, 8> argNames;
  516. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  517. const ParmVarDecl *parm = FD->getParamDecl(i);
  518. QualType ty = parm->getType();
  519. std::string typeQuals;
  520. if (ty->isPointerType()) {
  521. QualType pointeeTy = ty->getPointeeType();
  522. // Get address qualifier.
  523. addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(
  524. ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
  525. // Get argument type name.
  526. std::string typeName =
  527. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  528. // Turn "unsigned type" to "utype"
  529. std::string::size_type pos = typeName.find("unsigned");
  530. if (pointeeTy.isCanonical() && pos != std::string::npos)
  531. typeName.erase(pos+1, 8);
  532. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  533. std::string baseTypeName =
  534. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  535. Policy) +
  536. "*";
  537. // Turn "unsigned type" to "utype"
  538. pos = baseTypeName.find("unsigned");
  539. if (pos != std::string::npos)
  540. baseTypeName.erase(pos+1, 8);
  541. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  542. // Get argument type qualifiers:
  543. if (ty.isRestrictQualified())
  544. typeQuals = "restrict";
  545. if (pointeeTy.isConstQualified() ||
  546. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  547. typeQuals += typeQuals.empty() ? "const" : " const";
  548. if (pointeeTy.isVolatileQualified())
  549. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  550. } else {
  551. uint32_t AddrSpc = 0;
  552. bool isPipe = ty->isPipeType();
  553. if (ty->isImageType() || isPipe)
  554. AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
  555. addressQuals.push_back(
  556. llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc)));
  557. // Get argument type name.
  558. std::string typeName;
  559. if (isPipe)
  560. typeName = ty.getCanonicalType()->getAs<PipeType>()->getElementType()
  561. .getAsString(Policy);
  562. else
  563. typeName = ty.getUnqualifiedType().getAsString(Policy);
  564. // Turn "unsigned type" to "utype"
  565. std::string::size_type pos = typeName.find("unsigned");
  566. if (ty.isCanonical() && pos != std::string::npos)
  567. typeName.erase(pos+1, 8);
  568. std::string baseTypeName;
  569. if (isPipe)
  570. baseTypeName = ty.getCanonicalType()->getAs<PipeType>()
  571. ->getElementType().getCanonicalType()
  572. .getAsString(Policy);
  573. else
  574. baseTypeName =
  575. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  576. // Remove access qualifiers on images
  577. // (as they are inseparable from type in clang implementation,
  578. // but OpenCL spec provides a special query to get access qualifier
  579. // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
  580. if (ty->isImageType()) {
  581. removeImageAccessQualifier(typeName);
  582. removeImageAccessQualifier(baseTypeName);
  583. }
  584. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  585. // Turn "unsigned type" to "utype"
  586. pos = baseTypeName.find("unsigned");
  587. if (pos != std::string::npos)
  588. baseTypeName.erase(pos+1, 8);
  589. argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName));
  590. if (isPipe)
  591. typeQuals = "pipe";
  592. }
  593. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  594. // Get image and pipe access qualifier:
  595. if (ty->isImageType()|| ty->isPipeType()) {
  596. const Decl *PDecl = parm;
  597. if (auto *TD = dyn_cast<TypedefType>(ty))
  598. PDecl = TD->getDecl();
  599. const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
  600. if (A && A->isWriteOnly())
  601. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  602. else if (A && A->isReadWrite())
  603. accessQuals.push_back(llvm::MDString::get(Context, "read_write"));
  604. else
  605. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  606. } else
  607. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  608. // Get argument name.
  609. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  610. }
  611. Fn->setMetadata("kernel_arg_addr_space",
  612. llvm::MDNode::get(Context, addressQuals));
  613. Fn->setMetadata("kernel_arg_access_qual",
  614. llvm::MDNode::get(Context, accessQuals));
  615. Fn->setMetadata("kernel_arg_type",
  616. llvm::MDNode::get(Context, argTypeNames));
  617. Fn->setMetadata("kernel_arg_base_type",
  618. llvm::MDNode::get(Context, argBaseTypeNames));
  619. Fn->setMetadata("kernel_arg_type_qual",
  620. llvm::MDNode::get(Context, argTypeQuals));
  621. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  622. Fn->setMetadata("kernel_arg_name",
  623. llvm::MDNode::get(Context, argNames));
  624. }
  625. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  626. llvm::Function *Fn)
  627. {
  628. if (!FD->hasAttr<OpenCLKernelAttr>())
  629. return;
  630. llvm::LLVMContext &Context = getLLVMContext();
  631. GenOpenCLArgMetadata(FD, Fn, CGM, Context, Builder, getContext());
  632. if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) {
  633. QualType HintQTy = A->getTypeHint();
  634. const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>();
  635. bool IsSignedInteger =
  636. HintQTy->isSignedIntegerType() ||
  637. (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType());
  638. llvm::Metadata *AttrMDArgs[] = {
  639. llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
  640. CGM.getTypes().ConvertType(A->getTypeHint()))),
  641. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  642. llvm::IntegerType::get(Context, 32),
  643. llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
  644. Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
  645. }
  646. if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) {
  647. llvm::Metadata *AttrMDArgs[] = {
  648. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  649. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  650. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  651. Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
  652. }
  653. if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) {
  654. llvm::Metadata *AttrMDArgs[] = {
  655. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())),
  656. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())),
  657. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))};
  658. Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
  659. }
  660. if (const OpenCLIntelReqdSubGroupSizeAttr *A =
  661. FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
  662. llvm::Metadata *AttrMDArgs[] = {
  663. llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))};
  664. Fn->setMetadata("intel_reqd_sub_group_size",
  665. llvm::MDNode::get(Context, AttrMDArgs));
  666. }
  667. }
  668. /// Determine whether the function F ends with a return stmt.
  669. static bool endsWithReturn(const Decl* F) {
  670. const Stmt *Body = nullptr;
  671. if (auto *FD = dyn_cast_or_null<FunctionDecl>(F))
  672. Body = FD->getBody();
  673. else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
  674. Body = OMD->getBody();
  675. if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  676. auto LastStmt = CS->body_rbegin();
  677. if (LastStmt != CS->body_rend())
  678. return isa<ReturnStmt>(*LastStmt);
  679. }
  680. return false;
  681. }
  682. void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) {
  683. if (SanOpts.has(SanitizerKind::Thread)) {
  684. Fn->addFnAttr("sanitize_thread_no_checking_at_run_time");
  685. Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
  686. }
  687. }
  688. static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) {
  689. auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
  690. if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
  691. !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") ||
  692. (MD->getNumParams() != 1 && MD->getNumParams() != 2))
  693. return false;
  694. if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType())
  695. return false;
  696. if (MD->getNumParams() == 2) {
  697. auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>();
  698. if (!PT || !PT->isVoidPointerType() ||
  699. !PT->getPointeeType().isConstQualified())
  700. return false;
  701. }
  702. return true;
  703. }
  704. /// Return the UBSan prologue signature for \p FD if one is available.
  705. static llvm::Constant *getPrologueSignature(CodeGenModule &CGM,
  706. const FunctionDecl *FD) {
  707. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  708. if (!MD->isStatic())
  709. return nullptr;
  710. return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM);
  711. }
  712. void CodeGenFunction::StartFunction(GlobalDecl GD,
  713. QualType RetTy,
  714. llvm::Function *Fn,
  715. const CGFunctionInfo &FnInfo,
  716. const FunctionArgList &Args,
  717. SourceLocation Loc,
  718. SourceLocation StartLoc) {
  719. assert(!CurFn &&
  720. "Do not use a CodeGenFunction object for more than one function");
  721. const Decl *D = GD.getDecl();
  722. DidCallStackSave = false;
  723. CurCodeDecl = D;
  724. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  725. if (FD->usesSEHTry())
  726. CurSEHParent = FD;
  727. CurFuncDecl = (D ? D->getNonClosureContext() : nullptr);
  728. FnRetTy = RetTy;
  729. CurFn = Fn;
  730. CurFnInfo = &FnInfo;
  731. assert(CurFn->isDeclaration() && "Function already has body?");
  732. // If this function has been blacklisted for any of the enabled sanitizers,
  733. // disable the sanitizer for the function.
  734. do {
  735. #define SANITIZER(NAME, ID) \
  736. if (SanOpts.empty()) \
  737. break; \
  738. if (SanOpts.has(SanitizerKind::ID)) \
  739. if (CGM.isInSanitizerBlacklist(SanitizerKind::ID, Fn, Loc)) \
  740. SanOpts.set(SanitizerKind::ID, false);
  741. #include "clang/Basic/Sanitizers.def"
  742. #undef SANITIZER
  743. } while (0);
  744. if (D) {
  745. // Apply the no_sanitize* attributes to SanOpts.
  746. for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) {
  747. SanitizerMask mask = Attr->getMask();
  748. SanOpts.Mask &= ~mask;
  749. if (mask & SanitizerKind::Address)
  750. SanOpts.set(SanitizerKind::KernelAddress, false);
  751. if (mask & SanitizerKind::KernelAddress)
  752. SanOpts.set(SanitizerKind::Address, false);
  753. if (mask & SanitizerKind::HWAddress)
  754. SanOpts.set(SanitizerKind::KernelHWAddress, false);
  755. if (mask & SanitizerKind::KernelHWAddress)
  756. SanOpts.set(SanitizerKind::HWAddress, false);
  757. }
  758. }
  759. // Apply sanitizer attributes to the function.
  760. if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
  761. Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
  762. if (SanOpts.hasOneOf(SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress))
  763. Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
  764. if (SanOpts.has(SanitizerKind::Thread))
  765. Fn->addFnAttr(llvm::Attribute::SanitizeThread);
  766. if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
  767. Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
  768. if (SanOpts.has(SanitizerKind::SafeStack))
  769. Fn->addFnAttr(llvm::Attribute::SafeStack);
  770. if (SanOpts.has(SanitizerKind::ShadowCallStack))
  771. Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
  772. // Apply fuzzing attribute to the function.
  773. if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
  774. Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
  775. // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize,
  776. // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time.
  777. if (SanOpts.has(SanitizerKind::Thread)) {
  778. if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  779. IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
  780. if (OMD->getMethodFamily() == OMF_dealloc ||
  781. OMD->getMethodFamily() == OMF_initialize ||
  782. (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) {
  783. markAsIgnoreThreadCheckingAtRuntime(Fn);
  784. }
  785. }
  786. }
  787. // Ignore unrelated casts in STL allocate() since the allocator must cast
  788. // from void* to T* before object initialization completes. Don't match on the
  789. // namespace because not all allocators are in std::
  790. if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
  791. if (matchesStlAllocatorFn(D, getContext()))
  792. SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast;
  793. }
  794. // Apply xray attributes to the function (as a string, for now)
  795. if (D) {
  796. if (const auto *XRayAttr = D->getAttr<XRayInstrumentAttr>()) {
  797. if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has(
  798. XRayInstrKind::Function)) {
  799. if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction())
  800. Fn->addFnAttr("function-instrument", "xray-always");
  801. if (XRayAttr->neverXRayInstrument())
  802. Fn->addFnAttr("function-instrument", "xray-never");
  803. if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>())
  804. if (ShouldXRayInstrumentFunction())
  805. Fn->addFnAttr("xray-log-args",
  806. llvm::utostr(LogArgs->getArgumentCount()));
  807. }
  808. } else {
  809. if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc))
  810. Fn->addFnAttr(
  811. "xray-instruction-threshold",
  812. llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold));
  813. }
  814. }
  815. // Add no-jump-tables value.
  816. Fn->addFnAttr("no-jump-tables",
  817. llvm::toStringRef(CGM.getCodeGenOpts().NoUseJumpTables));
  818. // Add profile-sample-accurate value.
  819. if (CGM.getCodeGenOpts().ProfileSampleAccurate)
  820. Fn->addFnAttr("profile-sample-accurate");
  821. if (getLangOpts().OpenCL) {
  822. // Add metadata for a kernel function.
  823. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  824. EmitOpenCLKernelMetadata(FD, Fn);
  825. }
  826. // If we are checking function types, emit a function type signature as
  827. // prologue data.
  828. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) {
  829. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  830. if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) {
  831. // Remove any (C++17) exception specifications, to allow calling e.g. a
  832. // noexcept function through a non-noexcept pointer.
  833. auto ProtoTy =
  834. getContext().getFunctionTypeWithExceptionSpec(FD->getType(),
  835. EST_None);
  836. llvm::Constant *FTRTTIConst =
  837. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  838. llvm::Constant *FTRTTIConstEncoded =
  839. EncodeAddrForUseInPrologue(Fn, FTRTTIConst);
  840. llvm::Constant *PrologueStructElems[] = {PrologueSig,
  841. FTRTTIConstEncoded};
  842. llvm::Constant *PrologueStructConst =
  843. llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true);
  844. Fn->setPrologueData(PrologueStructConst);
  845. }
  846. }
  847. }
  848. // If we're checking nullability, we need to know whether we can check the
  849. // return value. Initialize the flag to 'true' and refine it in EmitParmDecl.
  850. if (SanOpts.has(SanitizerKind::NullabilityReturn)) {
  851. auto Nullability = FnRetTy->getNullability(getContext());
  852. if (Nullability && *Nullability == NullabilityKind::NonNull) {
  853. if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) &&
  854. CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>()))
  855. RetValNullabilityPrecondition =
  856. llvm::ConstantInt::getTrue(getLLVMContext());
  857. }
  858. }
  859. // If we're in C++ mode and the function name is "main", it is guaranteed
  860. // to be norecurse by the standard (3.6.1.3 "The function main shall not be
  861. // used within a program").
  862. if (getLangOpts().CPlusPlus)
  863. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  864. if (FD->isMain())
  865. Fn->addFnAttr(llvm::Attribute::NoRecurse);
  866. // If a custom alignment is used, force realigning to this alignment on
  867. // any main function which certainly will need it.
  868. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  869. if ((FD->isMain() || FD->isMSVCRTEntryPoint()) &&
  870. CGM.getCodeGenOpts().StackAlignment)
  871. Fn->addFnAttr("stackrealign");
  872. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  873. // Create a marker to make it easy to insert allocas into the entryblock
  874. // later. Don't create this with the builder, because we don't want it
  875. // folded.
  876. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  877. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB);
  878. ReturnBlock = getJumpDestInCurrentScope("return");
  879. Builder.SetInsertPoint(EntryBB);
  880. // If we're checking the return value, allocate space for a pointer to a
  881. // precise source location of the checked return statement.
  882. if (requiresReturnValueCheck()) {
  883. ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr");
  884. InitTempAlloca(ReturnLocation, llvm::ConstantPointerNull::get(Int8PtrTy));
  885. }
  886. // Emit subprogram debug descriptor.
  887. if (CGDebugInfo *DI = getDebugInfo()) {
  888. // Reconstruct the type from the argument list so that implicit parameters,
  889. // such as 'this' and 'vtt', show up in the debug info. Preserve the calling
  890. // convention.
  891. CallingConv CC = CallingConv::CC_C;
  892. if (auto *FD = dyn_cast_or_null<FunctionDecl>(D))
  893. if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
  894. CC = SrcFnTy->getCallConv();
  895. SmallVector<QualType, 16> ArgTypes;
  896. for (const VarDecl *VD : Args)
  897. ArgTypes.push_back(VD->getType());
  898. QualType FnType = getContext().getFunctionType(
  899. RetTy, ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
  900. DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, CurFuncIsThunk,
  901. Builder);
  902. }
  903. if (ShouldInstrumentFunction()) {
  904. if (CGM.getCodeGenOpts().InstrumentFunctions)
  905. CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter");
  906. if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining)
  907. CurFn->addFnAttr("instrument-function-entry-inlined",
  908. "__cyg_profile_func_enter");
  909. if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare)
  910. CurFn->addFnAttr("instrument-function-entry-inlined",
  911. "__cyg_profile_func_enter_bare");
  912. }
  913. // Since emitting the mcount call here impacts optimizations such as function
  914. // inlining, we just add an attribute to insert a mcount call in backend.
  915. // The attribute "counting-function" is set to mcount function name which is
  916. // architecture dependent.
  917. if (CGM.getCodeGenOpts().InstrumentForProfiling) {
  918. // Calls to fentry/mcount should not be generated if function has
  919. // the no_instrument_function attribute.
  920. if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) {
  921. if (CGM.getCodeGenOpts().CallFEntry)
  922. Fn->addFnAttr("fentry-call", "true");
  923. else {
  924. Fn->addFnAttr("instrument-function-entry-inlined",
  925. getTarget().getMCountName());
  926. }
  927. }
  928. }
  929. if (RetTy->isVoidType()) {
  930. // Void type; nothing to return.
  931. ReturnValue = Address::invalid();
  932. // Count the implicit return.
  933. if (!endsWithReturn(D))
  934. ++NumReturnExprs;
  935. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
  936. // Indirect return; emit returned value directly into sret slot.
  937. // This reduces code size, and affects correctness in C++.
  938. auto AI = CurFn->arg_begin();
  939. if (CurFnInfo->getReturnInfo().isSRetAfterThis())
  940. ++AI;
  941. ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
  942. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  943. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  944. // Load the sret pointer from the argument struct and return into that.
  945. unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex();
  946. llvm::Function::arg_iterator EI = CurFn->arg_end();
  947. --EI;
  948. llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
  949. Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
  950. ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
  951. } else {
  952. ReturnValue = CreateIRTemp(RetTy, "retval");
  953. // Tell the epilog emitter to autorelease the result. We do this
  954. // now so that various specialized functions can suppress it
  955. // during their IR-generation.
  956. if (getLangOpts().ObjCAutoRefCount &&
  957. !CurFnInfo->isReturnsRetained() &&
  958. RetTy->isObjCRetainableType())
  959. AutoreleaseResult = true;
  960. }
  961. EmitStartEHSpec(CurCodeDecl);
  962. PrologueCleanupDepth = EHStack.stable_begin();
  963. // Emit OpenMP specific initialization of the device functions.
  964. if (getLangOpts().OpenMP && CurCodeDecl)
  965. CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl);
  966. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  967. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  968. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  969. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  970. if (MD->getParent()->isLambda() &&
  971. MD->getOverloadedOperator() == OO_Call) {
  972. // We're in a lambda; figure out the captures.
  973. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  974. LambdaThisCaptureField);
  975. if (LambdaThisCaptureField) {
  976. // If the lambda captures the object referred to by '*this' - either by
  977. // value or by reference, make sure CXXThisValue points to the correct
  978. // object.
  979. // Get the lvalue for the field (which is a copy of the enclosing object
  980. // or contains the address of the enclosing object).
  981. LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  982. if (!LambdaThisCaptureField->getType()->isPointerType()) {
  983. // If the enclosing object was captured by value, just use its address.
  984. CXXThisValue = ThisFieldLValue.getAddress().getPointer();
  985. } else {
  986. // Load the lvalue pointed to by the field, since '*this' was captured
  987. // by reference.
  988. CXXThisValue =
  989. EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal();
  990. }
  991. }
  992. for (auto *FD : MD->getParent()->fields()) {
  993. if (FD->hasCapturedVLAType()) {
  994. auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD),
  995. SourceLocation()).getScalarVal();
  996. auto VAT = FD->getCapturedVLAType();
  997. VLASizeMap[VAT->getSizeExpr()] = ExprArg;
  998. }
  999. }
  1000. } else {
  1001. // Not in a lambda; just use 'this' from the method.
  1002. // FIXME: Should we generate a new load for each use of 'this'? The
  1003. // fast register allocator would be happier...
  1004. CXXThisValue = CXXABIThisValue;
  1005. }
  1006. // Check the 'this' pointer once per function, if it's available.
  1007. if (CXXABIThisValue) {
  1008. SanitizerSet SkippedChecks;
  1009. SkippedChecks.set(SanitizerKind::ObjectSize, true);
  1010. QualType ThisTy = MD->getThisType();
  1011. // If this is the call operator of a lambda with no capture-default, it
  1012. // may have a static invoker function, which may call this operator with
  1013. // a null 'this' pointer.
  1014. if (isLambdaCallOperator(MD) &&
  1015. MD->getParent()->getLambdaCaptureDefault() == LCD_None)
  1016. SkippedChecks.set(SanitizerKind::Null, true);
  1017. EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
  1018. : TCK_MemberCall,
  1019. Loc, CXXABIThisValue, ThisTy,
  1020. getContext().getTypeAlignInChars(ThisTy->getPointeeType()),
  1021. SkippedChecks);
  1022. }
  1023. }
  1024. // If any of the arguments have a variably modified type, make sure to
  1025. // emit the type size.
  1026. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1027. i != e; ++i) {
  1028. const VarDecl *VD = *i;
  1029. // Dig out the type as written from ParmVarDecls; it's unclear whether
  1030. // the standard (C99 6.9.1p10) requires this, but we're following the
  1031. // precedent set by gcc.
  1032. QualType Ty;
  1033. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  1034. Ty = PVD->getOriginalType();
  1035. else
  1036. Ty = VD->getType();
  1037. if (Ty->isVariablyModifiedType())
  1038. EmitVariablyModifiedType(Ty);
  1039. }
  1040. // Emit a location at the end of the prologue.
  1041. if (CGDebugInfo *DI = getDebugInfo())
  1042. DI->EmitLocation(Builder, StartLoc);
  1043. // TODO: Do we need to handle this in two places like we do with
  1044. // target-features/target-cpu?
  1045. if (CurFuncDecl)
  1046. if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>())
  1047. LargestVectorWidth = VecWidth->getVectorWidth();
  1048. }
  1049. void CodeGenFunction::EmitFunctionBody(const Stmt *Body) {
  1050. incrementProfileCounter(Body);
  1051. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  1052. EmitCompoundStmtWithoutScope(*S);
  1053. else
  1054. EmitStmt(Body);
  1055. }
  1056. /// When instrumenting to collect profile data, the counts for some blocks
  1057. /// such as switch cases need to not include the fall-through counts, so
  1058. /// emit a branch around the instrumentation code. When not instrumenting,
  1059. /// this just calls EmitBlock().
  1060. void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB,
  1061. const Stmt *S) {
  1062. llvm::BasicBlock *SkipCountBB = nullptr;
  1063. if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) {
  1064. // When instrumenting for profiling, the fallthrough to certain
  1065. // statements needs to skip over the instrumentation code so that we
  1066. // get an accurate count.
  1067. SkipCountBB = createBasicBlock("skipcount");
  1068. EmitBranch(SkipCountBB);
  1069. }
  1070. EmitBlock(BB);
  1071. uint64_t CurrentCount = getCurrentProfileCount();
  1072. incrementProfileCounter(S);
  1073. setCurrentProfileCount(getCurrentProfileCount() + CurrentCount);
  1074. if (SkipCountBB)
  1075. EmitBlock(SkipCountBB);
  1076. }
  1077. /// Tries to mark the given function nounwind based on the
  1078. /// non-existence of any throwing calls within it. We believe this is
  1079. /// lightweight enough to do at -O0.
  1080. static void TryMarkNoThrow(llvm::Function *F) {
  1081. // LLVM treats 'nounwind' on a function as part of the type, so we
  1082. // can't do this on functions that can be overwritten.
  1083. if (F->isInterposable()) return;
  1084. for (llvm::BasicBlock &BB : *F)
  1085. for (llvm::Instruction &I : BB)
  1086. if (I.mayThrow())
  1087. return;
  1088. F->setDoesNotThrow();
  1089. }
  1090. QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD,
  1091. FunctionArgList &Args) {
  1092. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1093. QualType ResTy = FD->getReturnType();
  1094. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  1095. if (MD && MD->isInstance()) {
  1096. if (CGM.getCXXABI().HasThisReturn(GD))
  1097. ResTy = MD->getThisType();
  1098. else if (CGM.getCXXABI().hasMostDerivedReturn(GD))
  1099. ResTy = CGM.getContext().VoidPtrTy;
  1100. CGM.getCXXABI().buildThisParam(*this, Args);
  1101. }
  1102. // The base version of an inheriting constructor whose constructed base is a
  1103. // virtual base is not passed any arguments (because it doesn't actually call
  1104. // the inherited constructor).
  1105. bool PassedParams = true;
  1106. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  1107. if (auto Inherited = CD->getInheritedConstructor())
  1108. PassedParams =
  1109. getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType());
  1110. if (PassedParams) {
  1111. for (auto *Param : FD->parameters()) {
  1112. Args.push_back(Param);
  1113. if (!Param->hasAttr<PassObjectSizeAttr>())
  1114. continue;
  1115. auto *Implicit = ImplicitParamDecl::Create(
  1116. getContext(), Param->getDeclContext(), Param->getLocation(),
  1117. /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other);
  1118. SizeArguments[Param] = Implicit;
  1119. Args.push_back(Implicit);
  1120. }
  1121. }
  1122. if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
  1123. CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args);
  1124. return ResTy;
  1125. }
  1126. static bool
  1127. shouldUseUndefinedBehaviorReturnOptimization(const FunctionDecl *FD,
  1128. const ASTContext &Context) {
  1129. QualType T = FD->getReturnType();
  1130. // Avoid the optimization for functions that return a record type with a
  1131. // trivial destructor or another trivially copyable type.
  1132. if (const RecordType *RT = T.getCanonicalType()->getAs<RecordType>()) {
  1133. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1134. return !ClassDecl->hasTrivialDestructor();
  1135. }
  1136. return !T.isTriviallyCopyableType(Context);
  1137. }
  1138. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1139. const CGFunctionInfo &FnInfo) {
  1140. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  1141. CurGD = GD;
  1142. FunctionArgList Args;
  1143. QualType ResTy = BuildFunctionArgList(GD, Args);
  1144. // Check if we should generate debug info for this function.
  1145. if (FD->hasAttr<NoDebugAttr>())
  1146. DebugInfo = nullptr; // disable debug info indefinitely for this function
  1147. // The function might not have a body if we're generating thunks for a
  1148. // function declaration.
  1149. SourceRange BodyRange;
  1150. if (Stmt *Body = FD->getBody())
  1151. BodyRange = Body->getSourceRange();
  1152. else
  1153. BodyRange = FD->getLocation();
  1154. CurEHLocation = BodyRange.getEnd();
  1155. // Use the location of the start of the function to determine where
  1156. // the function definition is located. By default use the location
  1157. // of the declaration as the location for the subprogram. A function
  1158. // may lack a declaration in the source code if it is created by code
  1159. // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
  1160. SourceLocation Loc = FD->getLocation();
  1161. // If this is a function specialization then use the pattern body
  1162. // as the location for the function.
  1163. if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern())
  1164. if (SpecDecl->hasBody(SpecDecl))
  1165. Loc = SpecDecl->getLocation();
  1166. Stmt *Body = FD->getBody();
  1167. // Initialize helper which will detect jumps which can cause invalid lifetime
  1168. // markers.
  1169. if (Body && ShouldEmitLifetimeMarkers)
  1170. Bypasses.Init(Body);
  1171. // Emit the standard function prologue.
  1172. StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin());
  1173. // Generate the body of the function.
  1174. PGO.assignRegionCounters(GD, CurFn);
  1175. if (isa<CXXDestructorDecl>(FD))
  1176. EmitDestructorBody(Args);
  1177. else if (isa<CXXConstructorDecl>(FD))
  1178. EmitConstructorBody(Args);
  1179. else if (getLangOpts().CUDA &&
  1180. !getLangOpts().CUDAIsDevice &&
  1181. FD->hasAttr<CUDAGlobalAttr>())
  1182. CGM.getCUDARuntime().emitDeviceStub(*this, Args);
  1183. else if (isa<CXXMethodDecl>(FD) &&
  1184. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  1185. // The lambda static invoker function is special, because it forwards or
  1186. // clones the body of the function call operator (but is actually static).
  1187. EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD));
  1188. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  1189. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  1190. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  1191. // Implicit copy-assignment gets the same special treatment as implicit
  1192. // copy-constructors.
  1193. emitImplicitAssignmentOperatorBody(Args);
  1194. } else if (Body) {
  1195. EmitFunctionBody(Body);
  1196. } else
  1197. llvm_unreachable("no definition for emitted function");
  1198. // C++11 [stmt.return]p2:
  1199. // Flowing off the end of a function [...] results in undefined behavior in
  1200. // a value-returning function.
  1201. // C11 6.9.1p12:
  1202. // If the '}' that terminates a function is reached, and the value of the
  1203. // function call is used by the caller, the behavior is undefined.
  1204. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock &&
  1205. !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) {
  1206. bool ShouldEmitUnreachable =
  1207. CGM.getCodeGenOpts().StrictReturn ||
  1208. shouldUseUndefinedBehaviorReturnOptimization(FD, getContext());
  1209. if (SanOpts.has(SanitizerKind::Return)) {
  1210. SanitizerScope SanScope(this);
  1211. llvm::Value *IsFalse = Builder.getFalse();
  1212. EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
  1213. SanitizerHandler::MissingReturn,
  1214. EmitCheckSourceLocation(FD->getLocation()), None);
  1215. } else if (ShouldEmitUnreachable) {
  1216. if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  1217. EmitTrapCall(llvm::Intrinsic::trap);
  1218. }
  1219. if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) {
  1220. Builder.CreateUnreachable();
  1221. Builder.ClearInsertionPoint();
  1222. }
  1223. }
  1224. // Emit the standard function epilogue.
  1225. FinishFunction(BodyRange.getEnd());
  1226. // If we haven't marked the function nothrow through other means, do
  1227. // a quick pass now to see if we can.
  1228. if (!CurFn->doesNotThrow())
  1229. TryMarkNoThrow(CurFn);
  1230. }
  1231. /// ContainsLabel - Return true if the statement contains a label in it. If
  1232. /// this statement is not executed normally, it not containing a label means
  1233. /// that we can just remove the code.
  1234. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  1235. // Null statement, not a label!
  1236. if (!S) return false;
  1237. // If this is a label, we have to emit the code, consider something like:
  1238. // if (0) { ... foo: bar(); } goto foo;
  1239. //
  1240. // TODO: If anyone cared, we could track __label__'s, since we know that you
  1241. // can't jump to one from outside their declared region.
  1242. if (isa<LabelStmt>(S))
  1243. return true;
  1244. // If this is a case/default statement, and we haven't seen a switch, we have
  1245. // to emit the code.
  1246. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  1247. return true;
  1248. // If this is a switch statement, we want to ignore cases below it.
  1249. if (isa<SwitchStmt>(S))
  1250. IgnoreCaseStmts = true;
  1251. // Scan subexpressions for verboten labels.
  1252. for (const Stmt *SubStmt : S->children())
  1253. if (ContainsLabel(SubStmt, IgnoreCaseStmts))
  1254. return true;
  1255. return false;
  1256. }
  1257. /// containsBreak - Return true if the statement contains a break out of it.
  1258. /// If the statement (recursively) contains a switch or loop with a break
  1259. /// inside of it, this is fine.
  1260. bool CodeGenFunction::containsBreak(const Stmt *S) {
  1261. // Null statement, not a label!
  1262. if (!S) return false;
  1263. // If this is a switch or loop that defines its own break scope, then we can
  1264. // include it and anything inside of it.
  1265. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  1266. isa<ForStmt>(S))
  1267. return false;
  1268. if (isa<BreakStmt>(S))
  1269. return true;
  1270. // Scan subexpressions for verboten breaks.
  1271. for (const Stmt *SubStmt : S->children())
  1272. if (containsBreak(SubStmt))
  1273. return true;
  1274. return false;
  1275. }
  1276. bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) {
  1277. if (!S) return false;
  1278. // Some statement kinds add a scope and thus never add a decl to the current
  1279. // scope. Note, this list is longer than the list of statements that might
  1280. // have an unscoped decl nested within them, but this way is conservatively
  1281. // correct even if more statement kinds are added.
  1282. if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
  1283. isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
  1284. isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
  1285. isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
  1286. return false;
  1287. if (isa<DeclStmt>(S))
  1288. return true;
  1289. for (const Stmt *SubStmt : S->children())
  1290. if (mightAddDeclToScope(SubStmt))
  1291. return true;
  1292. return false;
  1293. }
  1294. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1295. /// to a constant, or if it does but contains a label, return false. If it
  1296. /// constant folds return true and set the boolean result in Result.
  1297. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1298. bool &ResultBool,
  1299. bool AllowLabels) {
  1300. llvm::APSInt ResultInt;
  1301. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels))
  1302. return false;
  1303. ResultBool = ResultInt.getBoolValue();
  1304. return true;
  1305. }
  1306. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  1307. /// to a constant, or if it does but contains a label, return false. If it
  1308. /// constant folds return true and set the folded value.
  1309. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  1310. llvm::APSInt &ResultInt,
  1311. bool AllowLabels) {
  1312. // FIXME: Rename and handle conversion of other evaluatable things
  1313. // to bool.
  1314. Expr::EvalResult Result;
  1315. if (!Cond->EvaluateAsInt(Result, getContext()))
  1316. return false; // Not foldable, not integer or not fully evaluatable.
  1317. llvm::APSInt Int = Result.Val.getInt();
  1318. if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond))
  1319. return false; // Contains a label.
  1320. ResultInt = Int;
  1321. return true;
  1322. }
  1323. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  1324. /// statement) to the specified blocks. Based on the condition, this might try
  1325. /// to simplify the codegen of the conditional based on the branch.
  1326. ///
  1327. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  1328. llvm::BasicBlock *TrueBlock,
  1329. llvm::BasicBlock *FalseBlock,
  1330. uint64_t TrueCount) {
  1331. Cond = Cond->IgnoreParens();
  1332. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  1333. // Handle X && Y in a condition.
  1334. if (CondBOp->getOpcode() == BO_LAnd) {
  1335. // If we have "1 && X", simplify the code. "0 && X" would have constant
  1336. // folded if the case was simple enough.
  1337. bool ConstantBool = false;
  1338. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1339. ConstantBool) {
  1340. // br(1 && X) -> br(X).
  1341. incrementProfileCounter(CondBOp);
  1342. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1343. TrueCount);
  1344. }
  1345. // If we have "X && 1", simplify the code to use an uncond branch.
  1346. // "X && 0" would have been constant folded to 0.
  1347. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1348. ConstantBool) {
  1349. // br(X && 1) -> br(X).
  1350. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1351. TrueCount);
  1352. }
  1353. // Emit the LHS as a conditional. If the LHS conditional is false, we
  1354. // want to jump to the FalseBlock.
  1355. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  1356. // The counter tells us how often we evaluate RHS, and all of TrueCount
  1357. // can be propagated to that branch.
  1358. uint64_t RHSCount = getProfileCount(CondBOp->getRHS());
  1359. ConditionalEvaluation eval(*this);
  1360. {
  1361. ApplyDebugLocation DL(*this, Cond);
  1362. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount);
  1363. EmitBlock(LHSTrue);
  1364. }
  1365. incrementProfileCounter(CondBOp);
  1366. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1367. // Any temporaries created here are conditional.
  1368. eval.begin(*this);
  1369. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount);
  1370. eval.end(*this);
  1371. return;
  1372. }
  1373. if (CondBOp->getOpcode() == BO_LOr) {
  1374. // If we have "0 || X", simplify the code. "1 || X" would have constant
  1375. // folded if the case was simple enough.
  1376. bool ConstantBool = false;
  1377. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  1378. !ConstantBool) {
  1379. // br(0 || X) -> br(X).
  1380. incrementProfileCounter(CondBOp);
  1381. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock,
  1382. TrueCount);
  1383. }
  1384. // If we have "X || 0", simplify the code to use an uncond branch.
  1385. // "X || 1" would have been constant folded to 1.
  1386. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  1387. !ConstantBool) {
  1388. // br(X || 0) -> br(X).
  1389. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock,
  1390. TrueCount);
  1391. }
  1392. // Emit the LHS as a conditional. If the LHS conditional is true, we
  1393. // want to jump to the TrueBlock.
  1394. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  1395. // We have the count for entry to the RHS and for the whole expression
  1396. // being true, so we can divy up True count between the short circuit and
  1397. // the RHS.
  1398. uint64_t LHSCount =
  1399. getCurrentProfileCount() - getProfileCount(CondBOp->getRHS());
  1400. uint64_t RHSCount = TrueCount - LHSCount;
  1401. ConditionalEvaluation eval(*this);
  1402. {
  1403. ApplyDebugLocation DL(*this, Cond);
  1404. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount);
  1405. EmitBlock(LHSFalse);
  1406. }
  1407. incrementProfileCounter(CondBOp);
  1408. setCurrentProfileCount(getProfileCount(CondBOp->getRHS()));
  1409. // Any temporaries created here are conditional.
  1410. eval.begin(*this);
  1411. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount);
  1412. eval.end(*this);
  1413. return;
  1414. }
  1415. }
  1416. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  1417. // br(!x, t, f) -> br(x, f, t)
  1418. if (CondUOp->getOpcode() == UO_LNot) {
  1419. // Negate the count.
  1420. uint64_t FalseCount = getCurrentProfileCount() - TrueCount;
  1421. // Negate the condition and swap the destination blocks.
  1422. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock,
  1423. FalseCount);
  1424. }
  1425. }
  1426. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  1427. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  1428. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  1429. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  1430. ConditionalEvaluation cond(*this);
  1431. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock,
  1432. getProfileCount(CondOp));
  1433. // When computing PGO branch weights, we only know the overall count for
  1434. // the true block. This code is essentially doing tail duplication of the
  1435. // naive code-gen, introducing new edges for which counts are not
  1436. // available. Divide the counts proportionally between the LHS and RHS of
  1437. // the conditional operator.
  1438. uint64_t LHSScaledTrueCount = 0;
  1439. if (TrueCount) {
  1440. double LHSRatio =
  1441. getProfileCount(CondOp) / (double)getCurrentProfileCount();
  1442. LHSScaledTrueCount = TrueCount * LHSRatio;
  1443. }
  1444. cond.begin(*this);
  1445. EmitBlock(LHSBlock);
  1446. incrementProfileCounter(CondOp);
  1447. {
  1448. ApplyDebugLocation DL(*this, Cond);
  1449. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock,
  1450. LHSScaledTrueCount);
  1451. }
  1452. cond.end(*this);
  1453. cond.begin(*this);
  1454. EmitBlock(RHSBlock);
  1455. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock,
  1456. TrueCount - LHSScaledTrueCount);
  1457. cond.end(*this);
  1458. return;
  1459. }
  1460. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  1461. // Conditional operator handling can give us a throw expression as a
  1462. // condition for a case like:
  1463. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  1464. // Fold this to:
  1465. // br(c, throw x, br(y, t, f))
  1466. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  1467. return;
  1468. }
  1469. // If the branch has a condition wrapped by __builtin_unpredictable,
  1470. // create metadata that specifies that the branch is unpredictable.
  1471. // Don't bother if not optimizing because that metadata would not be used.
  1472. llvm::MDNode *Unpredictable = nullptr;
  1473. auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts());
  1474. if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
  1475. auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
  1476. if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
  1477. llvm::MDBuilder MDHelper(getLLVMContext());
  1478. Unpredictable = MDHelper.createUnpredictable();
  1479. }
  1480. }
  1481. // Create branch weights based on the number of times we get here and the
  1482. // number of times the condition should be true.
  1483. uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount);
  1484. llvm::MDNode *Weights =
  1485. createProfileWeights(TrueCount, CurrentCount - TrueCount);
  1486. // Emit the code with the fully general case.
  1487. llvm::Value *CondV;
  1488. {
  1489. ApplyDebugLocation DL(*this, Cond);
  1490. CondV = EvaluateExprAsBool(Cond);
  1491. }
  1492. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
  1493. }
  1494. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1495. /// specified stmt yet.
  1496. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  1497. CGM.ErrorUnsupported(S, Type);
  1498. }
  1499. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  1500. /// variable-length array whose elements have a non-zero bit-pattern.
  1501. ///
  1502. /// \param baseType the inner-most element type of the array
  1503. /// \param src - a char* pointing to the bit-pattern for a single
  1504. /// base element of the array
  1505. /// \param sizeInChars - the total size of the VLA, in chars
  1506. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  1507. Address dest, Address src,
  1508. llvm::Value *sizeInChars) {
  1509. CGBuilderTy &Builder = CGF.Builder;
  1510. CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
  1511. llvm::Value *baseSizeInChars
  1512. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity());
  1513. Address begin =
  1514. Builder.CreateElementBitCast(dest, CGF.Int8Ty, "vla.begin");
  1515. llvm::Value *end =
  1516. Builder.CreateInBoundsGEP(begin.getPointer(), sizeInChars, "vla.end");
  1517. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  1518. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  1519. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  1520. // Make a loop over the VLA. C99 guarantees that the VLA element
  1521. // count must be nonzero.
  1522. CGF.EmitBlock(loopBB);
  1523. llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur");
  1524. cur->addIncoming(begin.getPointer(), originBB);
  1525. CharUnits curAlign =
  1526. dest.getAlignment().alignmentOfArrayElement(baseSize);
  1527. // memcpy the individual element bit-pattern.
  1528. Builder.CreateMemCpy(Address(cur, curAlign), src, baseSizeInChars,
  1529. /*volatile*/ false);
  1530. // Go to the next element.
  1531. llvm::Value *next =
  1532. Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next");
  1533. // Leave if that's the end of the VLA.
  1534. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  1535. Builder.CreateCondBr(done, contBB, loopBB);
  1536. cur->addIncoming(next, loopBB);
  1537. CGF.EmitBlock(contBB);
  1538. }
  1539. void
  1540. CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) {
  1541. // Ignore empty classes in C++.
  1542. if (getLangOpts().CPlusPlus) {
  1543. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  1544. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  1545. return;
  1546. }
  1547. }
  1548. // Cast the dest ptr to the appropriate i8 pointer type.
  1549. if (DestPtr.getElementType() != Int8Ty)
  1550. DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
  1551. // Get size and alignment info for this aggregate.
  1552. CharUnits size = getContext().getTypeSizeInChars(Ty);
  1553. llvm::Value *SizeVal;
  1554. const VariableArrayType *vla;
  1555. // Don't bother emitting a zero-byte memset.
  1556. if (size.isZero()) {
  1557. // But note that getTypeInfo returns 0 for a VLA.
  1558. if (const VariableArrayType *vlaType =
  1559. dyn_cast_or_null<VariableArrayType>(
  1560. getContext().getAsArrayType(Ty))) {
  1561. auto VlaSize = getVLASize(vlaType);
  1562. SizeVal = VlaSize.NumElts;
  1563. CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type);
  1564. if (!eltSize.isOne())
  1565. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  1566. vla = vlaType;
  1567. } else {
  1568. return;
  1569. }
  1570. } else {
  1571. SizeVal = CGM.getSize(size);
  1572. vla = nullptr;
  1573. }
  1574. // If the type contains a pointer to data member we can't memset it to zero.
  1575. // Instead, create a null constant and copy it to the destination.
  1576. // TODO: there are other patterns besides zero that we can usefully memset,
  1577. // like -1, which happens to be the pattern used by member-pointers.
  1578. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  1579. // For a VLA, emit a single element, then splat that over the VLA.
  1580. if (vla) Ty = getContext().getBaseElementType(vla);
  1581. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  1582. llvm::GlobalVariable *NullVariable =
  1583. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  1584. /*isConstant=*/true,
  1585. llvm::GlobalVariable::PrivateLinkage,
  1586. NullConstant, Twine());
  1587. CharUnits NullAlign = DestPtr.getAlignment();
  1588. NullVariable->setAlignment(NullAlign.getQuantity());
  1589. Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()),
  1590. NullAlign);
  1591. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  1592. // Get and call the appropriate llvm.memcpy overload.
  1593. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false);
  1594. return;
  1595. }
  1596. // Otherwise, just memset the whole thing to zero. This is legal
  1597. // because in LLVM, all default initializers (other than the ones we just
  1598. // handled above) are guaranteed to have a bit pattern of all zeros.
  1599. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false);
  1600. }
  1601. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  1602. // Make sure that there is a block for the indirect goto.
  1603. if (!IndirectBranch)
  1604. GetIndirectGotoBlock();
  1605. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  1606. // Make sure the indirect branch includes all of the address-taken blocks.
  1607. IndirectBranch->addDestination(BB);
  1608. return llvm::BlockAddress::get(CurFn, BB);
  1609. }
  1610. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  1611. // If we already made the indirect branch for indirect goto, return its block.
  1612. if (IndirectBranch) return IndirectBranch->getParent();
  1613. CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto"));
  1614. // Create the PHI node that indirect gotos will add entries to.
  1615. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  1616. "indirect.goto.dest");
  1617. // Create the indirect branch instruction.
  1618. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  1619. return IndirectBranch->getParent();
  1620. }
  1621. /// Computes the length of an array in elements, as well as the base
  1622. /// element type and a properly-typed first element pointer.
  1623. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  1624. QualType &baseType,
  1625. Address &addr) {
  1626. const ArrayType *arrayType = origArrayType;
  1627. // If it's a VLA, we have to load the stored size. Note that
  1628. // this is the size of the VLA in bytes, not its size in elements.
  1629. llvm::Value *numVLAElements = nullptr;
  1630. if (isa<VariableArrayType>(arrayType)) {
  1631. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts;
  1632. // Walk into all VLAs. This doesn't require changes to addr,
  1633. // which has type T* where T is the first non-VLA element type.
  1634. do {
  1635. QualType elementType = arrayType->getElementType();
  1636. arrayType = getContext().getAsArrayType(elementType);
  1637. // If we only have VLA components, 'addr' requires no adjustment.
  1638. if (!arrayType) {
  1639. baseType = elementType;
  1640. return numVLAElements;
  1641. }
  1642. } while (isa<VariableArrayType>(arrayType));
  1643. // We get out here only if we find a constant array type
  1644. // inside the VLA.
  1645. }
  1646. // We have some number of constant-length arrays, so addr should
  1647. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  1648. // down to the first element of addr.
  1649. SmallVector<llvm::Value*, 8> gepIndices;
  1650. // GEP down to the array type.
  1651. llvm::ConstantInt *zero = Builder.getInt32(0);
  1652. gepIndices.push_back(zero);
  1653. uint64_t countFromCLAs = 1;
  1654. QualType eltType;
  1655. llvm::ArrayType *llvmArrayType =
  1656. dyn_cast<llvm::ArrayType>(addr.getElementType());
  1657. while (llvmArrayType) {
  1658. assert(isa<ConstantArrayType>(arrayType));
  1659. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1660. == llvmArrayType->getNumElements());
  1661. gepIndices.push_back(zero);
  1662. countFromCLAs *= llvmArrayType->getNumElements();
  1663. eltType = arrayType->getElementType();
  1664. llvmArrayType =
  1665. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1666. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1667. assert((!llvmArrayType || arrayType) &&
  1668. "LLVM and Clang types are out-of-synch");
  1669. }
  1670. if (arrayType) {
  1671. // From this point onwards, the Clang array type has been emitted
  1672. // as some other type (probably a packed struct). Compute the array
  1673. // size, and just emit the 'begin' expression as a bitcast.
  1674. while (arrayType) {
  1675. countFromCLAs *=
  1676. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1677. eltType = arrayType->getElementType();
  1678. arrayType = getContext().getAsArrayType(eltType);
  1679. }
  1680. llvm::Type *baseType = ConvertType(eltType);
  1681. addr = Builder.CreateElementBitCast(addr, baseType, "array.begin");
  1682. } else {
  1683. // Create the actual GEP.
  1684. addr = Address(Builder.CreateInBoundsGEP(addr.getPointer(),
  1685. gepIndices, "array.begin"),
  1686. addr.getAlignment());
  1687. }
  1688. baseType = eltType;
  1689. llvm::Value *numElements
  1690. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1691. // If we had any VLA dimensions, factor them in.
  1692. if (numVLAElements)
  1693. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1694. return numElements;
  1695. }
  1696. CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) {
  1697. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1698. assert(vla && "type was not a variable array type!");
  1699. return getVLASize(vla);
  1700. }
  1701. CodeGenFunction::VlaSizePair
  1702. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1703. // The number of elements so far; always size_t.
  1704. llvm::Value *numElements = nullptr;
  1705. QualType elementType;
  1706. do {
  1707. elementType = type->getElementType();
  1708. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1709. assert(vlaSize && "no size for VLA!");
  1710. assert(vlaSize->getType() == SizeTy);
  1711. if (!numElements) {
  1712. numElements = vlaSize;
  1713. } else {
  1714. // It's undefined behavior if this wraps around, so mark it that way.
  1715. // FIXME: Teach -fsanitize=undefined to trap this.
  1716. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1717. }
  1718. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1719. return { numElements, elementType };
  1720. }
  1721. CodeGenFunction::VlaSizePair
  1722. CodeGenFunction::getVLAElements1D(QualType type) {
  1723. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1724. assert(vla && "type was not a variable array type!");
  1725. return getVLAElements1D(vla);
  1726. }
  1727. CodeGenFunction::VlaSizePair
  1728. CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) {
  1729. llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()];
  1730. assert(VlaSize && "no size for VLA!");
  1731. assert(VlaSize->getType() == SizeTy);
  1732. return { VlaSize, Vla->getElementType() };
  1733. }
  1734. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1735. assert(type->isVariablyModifiedType() &&
  1736. "Must pass variably modified type to EmitVLASizes!");
  1737. EnsureInsertPoint();
  1738. // We're going to walk down into the type and look for VLA
  1739. // expressions.
  1740. do {
  1741. assert(type->isVariablyModifiedType());
  1742. const Type *ty = type.getTypePtr();
  1743. switch (ty->getTypeClass()) {
  1744. #define TYPE(Class, Base)
  1745. #define ABSTRACT_TYPE(Class, Base)
  1746. #define NON_CANONICAL_TYPE(Class, Base)
  1747. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1748. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1749. #include "clang/AST/TypeNodes.def"
  1750. llvm_unreachable("unexpected dependent type!");
  1751. // These types are never variably-modified.
  1752. case Type::Builtin:
  1753. case Type::Complex:
  1754. case Type::Vector:
  1755. case Type::ExtVector:
  1756. case Type::Record:
  1757. case Type::Enum:
  1758. case Type::Elaborated:
  1759. case Type::TemplateSpecialization:
  1760. case Type::ObjCTypeParam:
  1761. case Type::ObjCObject:
  1762. case Type::ObjCInterface:
  1763. case Type::ObjCObjectPointer:
  1764. llvm_unreachable("type class is never variably-modified!");
  1765. case Type::Adjusted:
  1766. type = cast<AdjustedType>(ty)->getAdjustedType();
  1767. break;
  1768. case Type::Decayed:
  1769. type = cast<DecayedType>(ty)->getPointeeType();
  1770. break;
  1771. case Type::Pointer:
  1772. type = cast<PointerType>(ty)->getPointeeType();
  1773. break;
  1774. case Type::BlockPointer:
  1775. type = cast<BlockPointerType>(ty)->getPointeeType();
  1776. break;
  1777. case Type::LValueReference:
  1778. case Type::RValueReference:
  1779. type = cast<ReferenceType>(ty)->getPointeeType();
  1780. break;
  1781. case Type::MemberPointer:
  1782. type = cast<MemberPointerType>(ty)->getPointeeType();
  1783. break;
  1784. case Type::ConstantArray:
  1785. case Type::IncompleteArray:
  1786. // Losing element qualification here is fine.
  1787. type = cast<ArrayType>(ty)->getElementType();
  1788. break;
  1789. case Type::VariableArray: {
  1790. // Losing element qualification here is fine.
  1791. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1792. // Unknown size indication requires no size computation.
  1793. // Otherwise, evaluate and record it.
  1794. if (const Expr *size = vat->getSizeExpr()) {
  1795. // It's possible that we might have emitted this already,
  1796. // e.g. with a typedef and a pointer to it.
  1797. llvm::Value *&entry = VLASizeMap[size];
  1798. if (!entry) {
  1799. llvm::Value *Size = EmitScalarExpr(size);
  1800. // C11 6.7.6.2p5:
  1801. // If the size is an expression that is not an integer constant
  1802. // expression [...] each time it is evaluated it shall have a value
  1803. // greater than zero.
  1804. if (SanOpts.has(SanitizerKind::VLABound) &&
  1805. size->getType()->isSignedIntegerType()) {
  1806. SanitizerScope SanScope(this);
  1807. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1808. llvm::Constant *StaticArgs[] = {
  1809. EmitCheckSourceLocation(size->getBeginLoc()),
  1810. EmitCheckTypeDescriptor(size->getType())};
  1811. EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero),
  1812. SanitizerKind::VLABound),
  1813. SanitizerHandler::VLABoundNotPositive, StaticArgs, Size);
  1814. }
  1815. // Always zexting here would be wrong if it weren't
  1816. // undefined behavior to have a negative bound.
  1817. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1818. }
  1819. }
  1820. type = vat->getElementType();
  1821. break;
  1822. }
  1823. case Type::FunctionProto:
  1824. case Type::FunctionNoProto:
  1825. type = cast<FunctionType>(ty)->getReturnType();
  1826. break;
  1827. case Type::Paren:
  1828. case Type::TypeOf:
  1829. case Type::UnaryTransform:
  1830. case Type::Attributed:
  1831. case Type::SubstTemplateTypeParm:
  1832. case Type::PackExpansion:
  1833. // Keep walking after single level desugaring.
  1834. type = type.getSingleStepDesugaredType(getContext());
  1835. break;
  1836. case Type::Typedef:
  1837. case Type::Decltype:
  1838. case Type::Auto:
  1839. case Type::DeducedTemplateSpecialization:
  1840. // Stop walking: nothing to do.
  1841. return;
  1842. case Type::TypeOfExpr:
  1843. // Stop walking: emit typeof expression.
  1844. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1845. return;
  1846. case Type::Atomic:
  1847. type = cast<AtomicType>(ty)->getValueType();
  1848. break;
  1849. case Type::Pipe:
  1850. type = cast<PipeType>(ty)->getElementType();
  1851. break;
  1852. }
  1853. } while (type->isVariablyModifiedType());
  1854. }
  1855. Address CodeGenFunction::EmitVAListRef(const Expr* E) {
  1856. if (getContext().getBuiltinVaListType()->isArrayType())
  1857. return EmitPointerWithAlignment(E);
  1858. return EmitLValue(E).getAddress();
  1859. }
  1860. Address CodeGenFunction::EmitMSVAListRef(const Expr *E) {
  1861. return EmitLValue(E).getAddress();
  1862. }
  1863. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1864. const APValue &Init) {
  1865. assert(!Init.isUninit() && "Invalid DeclRefExpr initializer!");
  1866. if (CGDebugInfo *Dbg = getDebugInfo())
  1867. if (CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  1868. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1869. }
  1870. CodeGenFunction::PeepholeProtection
  1871. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1872. // At the moment, the only aggressive peephole we do in IR gen
  1873. // is trunc(zext) folding, but if we add more, we can easily
  1874. // extend this protection.
  1875. if (!rvalue.isScalar()) return PeepholeProtection();
  1876. llvm::Value *value = rvalue.getScalarVal();
  1877. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1878. // Just make an extra bitcast.
  1879. assert(HaveInsertPoint());
  1880. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1881. Builder.GetInsertBlock());
  1882. PeepholeProtection protection;
  1883. protection.Inst = inst;
  1884. return protection;
  1885. }
  1886. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1887. if (!protection.Inst) return;
  1888. // In theory, we could try to duplicate the peepholes now, but whatever.
  1889. protection.Inst->eraseFromParent();
  1890. }
  1891. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1892. QualType Ty, SourceLocation Loc,
  1893. SourceLocation AssumptionLoc,
  1894. llvm::Value *Alignment,
  1895. llvm::Value *OffsetValue) {
  1896. llvm::Value *TheCheck;
  1897. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1898. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1899. if (SanOpts.has(SanitizerKind::Alignment)) {
  1900. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1901. OffsetValue, TheCheck, Assumption);
  1902. }
  1903. }
  1904. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1905. QualType Ty, SourceLocation Loc,
  1906. SourceLocation AssumptionLoc,
  1907. unsigned Alignment,
  1908. llvm::Value *OffsetValue) {
  1909. llvm::Value *TheCheck;
  1910. llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption(
  1911. CGM.getDataLayout(), PtrValue, Alignment, OffsetValue, &TheCheck);
  1912. if (SanOpts.has(SanitizerKind::Alignment)) {
  1913. llvm::Value *AlignmentVal = llvm::ConstantInt::get(IntPtrTy, Alignment);
  1914. EmitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, AlignmentVal,
  1915. OffsetValue, TheCheck, Assumption);
  1916. }
  1917. }
  1918. void CodeGenFunction::EmitAlignmentAssumption(llvm::Value *PtrValue,
  1919. const Expr *E,
  1920. SourceLocation AssumptionLoc,
  1921. unsigned Alignment,
  1922. llvm::Value *OffsetValue) {
  1923. if (auto *CE = dyn_cast<CastExpr>(E))
  1924. E = CE->getSubExprAsWritten();
  1925. QualType Ty = E->getType();
  1926. SourceLocation Loc = E->getExprLoc();
  1927. EmitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment,
  1928. OffsetValue);
  1929. }
  1930. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn,
  1931. llvm::Value *AnnotatedVal,
  1932. StringRef AnnotationStr,
  1933. SourceLocation Location) {
  1934. llvm::Value *Args[4] = {
  1935. AnnotatedVal,
  1936. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1937. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1938. CGM.EmitAnnotationLineNo(Location)
  1939. };
  1940. return Builder.CreateCall(AnnotationFn, Args);
  1941. }
  1942. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1943. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1944. // FIXME We create a new bitcast for every annotation because that's what
  1945. // llvm-gcc was doing.
  1946. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1947. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1948. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1949. I->getAnnotation(), D->getLocation());
  1950. }
  1951. Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1952. Address Addr) {
  1953. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1954. llvm::Value *V = Addr.getPointer();
  1955. llvm::Type *VTy = V->getType();
  1956. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1957. CGM.Int8PtrTy);
  1958. for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
  1959. // FIXME Always emit the cast inst so we can differentiate between
  1960. // annotation on the first field of a struct and annotation on the struct
  1961. // itself.
  1962. if (VTy != CGM.Int8PtrTy)
  1963. V = Builder.CreateBitCast(V, CGM.Int8PtrTy);
  1964. V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation());
  1965. V = Builder.CreateBitCast(V, VTy);
  1966. }
  1967. return Address(V, Addr.getAlignment());
  1968. }
  1969. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }
  1970. CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF)
  1971. : CGF(CGF) {
  1972. assert(!CGF->IsSanitizerScope);
  1973. CGF->IsSanitizerScope = true;
  1974. }
  1975. CodeGenFunction::SanitizerScope::~SanitizerScope() {
  1976. CGF->IsSanitizerScope = false;
  1977. }
  1978. void CodeGenFunction::InsertHelper(llvm::Instruction *I,
  1979. const llvm::Twine &Name,
  1980. llvm::BasicBlock *BB,
  1981. llvm::BasicBlock::iterator InsertPt) const {
  1982. LoopStack.InsertHelper(I);
  1983. if (IsSanitizerScope)
  1984. CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I);
  1985. }
  1986. void CGBuilderInserter::InsertHelper(
  1987. llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB,
  1988. llvm::BasicBlock::iterator InsertPt) const {
  1989. llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
  1990. if (CGF)
  1991. CGF->InsertHelper(I, Name, BB, InsertPt);
  1992. }
  1993. static bool hasRequiredFeatures(const SmallVectorImpl<StringRef> &ReqFeatures,
  1994. CodeGenModule &CGM, const FunctionDecl *FD,
  1995. std::string &FirstMissing) {
  1996. // If there aren't any required features listed then go ahead and return.
  1997. if (ReqFeatures.empty())
  1998. return false;
  1999. // Now build up the set of caller features and verify that all the required
  2000. // features are there.
  2001. llvm::StringMap<bool> CallerFeatureMap;
  2002. CGM.getFunctionFeatureMap(CallerFeatureMap, GlobalDecl().getWithDecl(FD));
  2003. // If we have at least one of the features in the feature list return
  2004. // true, otherwise return false.
  2005. return std::all_of(
  2006. ReqFeatures.begin(), ReqFeatures.end(), [&](StringRef Feature) {
  2007. SmallVector<StringRef, 1> OrFeatures;
  2008. Feature.split(OrFeatures, '|');
  2009. return llvm::any_of(OrFeatures, [&](StringRef Feature) {
  2010. if (!CallerFeatureMap.lookup(Feature)) {
  2011. FirstMissing = Feature.str();
  2012. return false;
  2013. }
  2014. return true;
  2015. });
  2016. });
  2017. }
  2018. // Emits an error if we don't have a valid set of target features for the
  2019. // called function.
  2020. void CodeGenFunction::checkTargetFeatures(const CallExpr *E,
  2021. const FunctionDecl *TargetDecl) {
  2022. // Early exit if this is an indirect call.
  2023. if (!TargetDecl)
  2024. return;
  2025. // Get the current enclosing function if it exists. If it doesn't
  2026. // we can't check the target features anyhow.
  2027. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl);
  2028. if (!FD)
  2029. return;
  2030. // Grab the required features for the call. For a builtin this is listed in
  2031. // the td file with the default cpu, for an always_inline function this is any
  2032. // listed cpu and any listed features.
  2033. unsigned BuiltinID = TargetDecl->getBuiltinID();
  2034. std::string MissingFeature;
  2035. if (BuiltinID) {
  2036. SmallVector<StringRef, 1> ReqFeatures;
  2037. const char *FeatureList =
  2038. CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  2039. // Return if the builtin doesn't have any required features.
  2040. if (!FeatureList || StringRef(FeatureList) == "")
  2041. return;
  2042. StringRef(FeatureList).split(ReqFeatures, ',');
  2043. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  2044. CGM.getDiags().Report(E->getBeginLoc(), diag::err_builtin_needs_feature)
  2045. << TargetDecl->getDeclName()
  2046. << CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID);
  2047. } else if (TargetDecl->hasAttr<TargetAttr>() ||
  2048. TargetDecl->hasAttr<CPUSpecificAttr>()) {
  2049. // Get the required features for the callee.
  2050. const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>();
  2051. TargetAttr::ParsedTargetAttr ParsedAttr = CGM.filterFunctionTargetAttrs(TD);
  2052. SmallVector<StringRef, 1> ReqFeatures;
  2053. llvm::StringMap<bool> CalleeFeatureMap;
  2054. CGM.getFunctionFeatureMap(CalleeFeatureMap, TargetDecl);
  2055. for (const auto &F : ParsedAttr.Features) {
  2056. if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1)))
  2057. ReqFeatures.push_back(StringRef(F).substr(1));
  2058. }
  2059. for (const auto &F : CalleeFeatureMap) {
  2060. // Only positive features are "required".
  2061. if (F.getValue())
  2062. ReqFeatures.push_back(F.getKey());
  2063. }
  2064. if (!hasRequiredFeatures(ReqFeatures, CGM, FD, MissingFeature))
  2065. CGM.getDiags().Report(E->getBeginLoc(), diag::err_function_needs_feature)
  2066. << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
  2067. }
  2068. }
  2069. void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) {
  2070. if (!CGM.getCodeGenOpts().SanitizeStats)
  2071. return;
  2072. llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
  2073. IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
  2074. CGM.getSanStats().create(IRB, SSK);
  2075. }
  2076. llvm::Value *
  2077. CodeGenFunction::FormResolverCondition(const MultiVersionResolverOption &RO) {
  2078. llvm::Value *Condition = nullptr;
  2079. if (!RO.Conditions.Architecture.empty())
  2080. Condition = EmitX86CpuIs(RO.Conditions.Architecture);
  2081. if (!RO.Conditions.Features.empty()) {
  2082. llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features);
  2083. Condition =
  2084. Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond;
  2085. }
  2086. return Condition;
  2087. }
  2088. static void CreateMultiVersionResolverReturn(CodeGenModule &CGM,
  2089. llvm::Function *Resolver,
  2090. CGBuilderTy &Builder,
  2091. llvm::Function *FuncToReturn,
  2092. bool SupportsIFunc) {
  2093. if (SupportsIFunc) {
  2094. Builder.CreateRet(FuncToReturn);
  2095. return;
  2096. }
  2097. llvm::SmallVector<llvm::Value *, 10> Args;
  2098. llvm::for_each(Resolver->args(),
  2099. [&](llvm::Argument &Arg) { Args.push_back(&Arg); });
  2100. llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args);
  2101. Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
  2102. if (Resolver->getReturnType()->isVoidTy())
  2103. Builder.CreateRetVoid();
  2104. else
  2105. Builder.CreateRet(Result);
  2106. }
  2107. void CodeGenFunction::EmitMultiVersionResolver(
  2108. llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) {
  2109. assert((getContext().getTargetInfo().getTriple().getArch() ==
  2110. llvm::Triple::x86 ||
  2111. getContext().getTargetInfo().getTriple().getArch() ==
  2112. llvm::Triple::x86_64) &&
  2113. "Only implemented for x86 targets");
  2114. bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
  2115. // Main function's basic block.
  2116. llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
  2117. Builder.SetInsertPoint(CurBlock);
  2118. EmitX86CpuInit();
  2119. for (const MultiVersionResolverOption &RO : Options) {
  2120. Builder.SetInsertPoint(CurBlock);
  2121. llvm::Value *Condition = FormResolverCondition(RO);
  2122. // The 'default' or 'generic' case.
  2123. if (!Condition) {
  2124. assert(&RO == Options.end() - 1 &&
  2125. "Default or Generic case must be last");
  2126. CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function,
  2127. SupportsIFunc);
  2128. return;
  2129. }
  2130. llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver);
  2131. CGBuilderTy RetBuilder(*this, RetBlock);
  2132. CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function,
  2133. SupportsIFunc);
  2134. CurBlock = createBasicBlock("resolver_else", Resolver);
  2135. Builder.CreateCondBr(Condition, RetBlock, CurBlock);
  2136. }
  2137. // If no generic/default, emit an unreachable.
  2138. Builder.SetInsertPoint(CurBlock);
  2139. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2140. TrapCall->setDoesNotReturn();
  2141. TrapCall->setDoesNotThrow();
  2142. Builder.CreateUnreachable();
  2143. Builder.ClearInsertionPoint();
  2144. }
  2145. // Loc - where the diagnostic will point, where in the source code this
  2146. // alignment has failed.
  2147. // SecondaryLoc - if present (will be present if sufficiently different from
  2148. // Loc), the diagnostic will additionally point a "Note:" to this location.
  2149. // It should be the location where the __attribute__((assume_aligned))
  2150. // was written e.g.
  2151. void CodeGenFunction::EmitAlignmentAssumptionCheck(
  2152. llvm::Value *Ptr, QualType Ty, SourceLocation Loc,
  2153. SourceLocation SecondaryLoc, llvm::Value *Alignment,
  2154. llvm::Value *OffsetValue, llvm::Value *TheCheck,
  2155. llvm::Instruction *Assumption) {
  2156. assert(Assumption && isa<llvm::CallInst>(Assumption) &&
  2157. cast<llvm::CallInst>(Assumption)->getCalledValue() ==
  2158. llvm::Intrinsic::getDeclaration(
  2159. Builder.GetInsertBlock()->getParent()->getParent(),
  2160. llvm::Intrinsic::assume) &&
  2161. "Assumption should be a call to llvm.assume().");
  2162. assert(&(Builder.GetInsertBlock()->back()) == Assumption &&
  2163. "Assumption should be the last instruction of the basic block, "
  2164. "since the basic block is still being generated.");
  2165. if (!SanOpts.has(SanitizerKind::Alignment))
  2166. return;
  2167. // Don't check pointers to volatile data. The behavior here is implementation-
  2168. // defined.
  2169. if (Ty->getPointeeType().isVolatileQualified())
  2170. return;
  2171. // We need to temorairly remove the assumption so we can insert the
  2172. // sanitizer check before it, else the check will be dropped by optimizations.
  2173. Assumption->removeFromParent();
  2174. {
  2175. SanitizerScope SanScope(this);
  2176. if (!OffsetValue)
  2177. OffsetValue = Builder.getInt1(0); // no offset.
  2178. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc),
  2179. EmitCheckSourceLocation(SecondaryLoc),
  2180. EmitCheckTypeDescriptor(Ty)};
  2181. llvm::Value *DynamicData[] = {EmitCheckValue(Ptr),
  2182. EmitCheckValue(Alignment),
  2183. EmitCheckValue(OffsetValue)};
  2184. EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
  2185. SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
  2186. }
  2187. // We are now in the (new, empty) "cont" basic block.
  2188. // Reintroduce the assumption.
  2189. Builder.Insert(Assumption);
  2190. // FIXME: Assumption still has it's original basic block as it's Parent.
  2191. }
  2192. llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) {
  2193. if (CGDebugInfo *DI = getDebugInfo())
  2194. return DI->SourceLocToDebugLoc(Location);
  2195. return llvm::DebugLoc();
  2196. }