CodeGenFunction.cpp 93 KB

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