blob: 13c02f21813541a34e438bbe7bb09e88e4fa9a62 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Stmt nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "CodeGenFunction.h"
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000015#include "CGDebugInfo.h"
16#include "CodeGenModule.h"
Peter Collingbourne4b93d662011-02-19 23:03:58 +000017#include "TargetInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/StmtVisitor.h"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080019#include "clang/Basic/Builtins.h"
Chris Lattner7d22bf02009-03-05 08:04:57 +000020#include "clang/Basic/PrettyStackTrace.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000021#include "clang/Basic/TargetInfo.h"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070022#include "clang/Sema/LoopHint.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "clang/Sema/SemaDiagnostic.h"
Anders Carlssonfb1aeb82008-02-05 16:35:33 +000024#include "llvm/ADT/StringExtras.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
28#include "llvm/IR/Intrinsics.h"
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -080029#include "llvm/IR/MDBuilder.h"
30
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32using namespace CodeGen;
33
34//===----------------------------------------------------------------------===//
35// Statement Emission
36//===----------------------------------------------------------------------===//
37
Daniel Dunbar09124252008-11-12 08:21:33 +000038void CodeGenFunction::EmitStopPoint(const Stmt *S) {
Anders Carlssone896d982009-02-13 08:11:52 +000039 if (CGDebugInfo *DI = getDebugInfo()) {
Eric Christopher73fb3502011-10-13 21:45:18 +000040 SourceLocation Loc;
Adrian Prantl2736f2e2013-06-18 00:27:36 +000041 Loc = S->getLocStart();
Eric Christopher73fb3502011-10-13 21:45:18 +000042 DI->EmitLocation(Builder, Loc);
Adrian Prantlfa6b0792013-05-02 17:30:20 +000043
Adrian Prantl40080882013-05-07 22:26:03 +000044 LastStopPoint = Loc;
Daniel Dunbar09124252008-11-12 08:21:33 +000045 }
46}
47
Reid Spencer5f016e22007-07-11 17:01:13 +000048void CodeGenFunction::EmitStmt(const Stmt *S) {
49 assert(S && "Null statement?");
Stephen Hines651f13c2014-04-23 16:59:28 -070050 PGO.setCurrentStmt(S);
Daniel Dunbara448fb22008-11-11 23:11:34 +000051
Eric Christopherf9aac382011-09-26 15:03:19 +000052 // These statements have their own debug info handling.
Daniel Dunbar09124252008-11-12 08:21:33 +000053 if (EmitSimpleStmt(S))
54 return;
55
Daniel Dunbard286f052009-07-19 06:58:07 +000056 // Check if we are generating unreachable code.
57 if (!HaveInsertPoint()) {
58 // If so, and the statement doesn't contain a label, then we do not need to
59 // generate actual code. This is safe because (1) the current point is
60 // unreachable, so we don't need to execute the code, and (2) we've already
61 // handled the statements which update internal data structures (like the
62 // local variable map) which could be used by subsequent statements.
63 if (!ContainsLabel(S)) {
64 // Verify that any decl statements were handled as simple, they may be in
65 // scope of subsequent reachable statements.
66 assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
67 return;
68 }
69
70 // Otherwise, make a new block to hold the code.
71 EnsureInsertPoint();
72 }
73
Daniel Dunbar09124252008-11-12 08:21:33 +000074 // Generate a stoppoint if we are emitting debug info.
75 EmitStopPoint(S);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000076
Reid Spencer5f016e22007-07-11 17:01:13 +000077 switch (S->getStmtClass()) {
John McCall2a416372010-12-05 02:00:02 +000078 case Stmt::NoStmtClass:
79 case Stmt::CXXCatchStmtClass:
John Wiegley28bbe4b2011-04-28 01:08:34 +000080 case Stmt::SEHExceptStmtClass:
81 case Stmt::SEHFinallyStmtClass:
Douglas Gregorba0513d2011-10-25 01:33:02 +000082 case Stmt::MSDependentExistsStmtClass:
John McCall2a416372010-12-05 02:00:02 +000083 llvm_unreachable("invalid statement class to emit generically");
84 case Stmt::NullStmtClass:
85 case Stmt::CompoundStmtClass:
86 case Stmt::DeclStmtClass:
87 case Stmt::LabelStmtClass:
Richard Smith534986f2012-04-14 00:33:13 +000088 case Stmt::AttributedStmtClass:
John McCall2a416372010-12-05 02:00:02 +000089 case Stmt::GotoStmtClass:
90 case Stmt::BreakStmtClass:
91 case Stmt::ContinueStmtClass:
92 case Stmt::DefaultStmtClass:
93 case Stmt::CaseStmtClass:
Stephen Hines0e2c34f2015-03-23 12:09:02 -070094 case Stmt::SEHLeaveStmtClass:
John McCall2a416372010-12-05 02:00:02 +000095 llvm_unreachable("should have emitted these statements as simple");
Daniel Dunbarcd5e60e2009-07-19 08:23:12 +000096
John McCall2a416372010-12-05 02:00:02 +000097#define STMT(Type, Base)
98#define ABSTRACT_STMT(Op)
99#define EXPR(Type, Base) \
100 case Stmt::Type##Class:
101#include "clang/AST/StmtNodes.inc"
John McCallcd5b22e2011-01-12 03:41:02 +0000102 {
103 // Remember the block we came in on.
104 llvm::BasicBlock *incoming = Builder.GetInsertBlock();
105 assert(incoming && "expression emission must have an insertion point");
106
John McCall2a416372010-12-05 02:00:02 +0000107 EmitIgnoredExpr(cast<Expr>(S));
Mike Stump1eb44332009-09-09 15:08:12 +0000108
John McCallcd5b22e2011-01-12 03:41:02 +0000109 llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
110 assert(outgoing && "expression emission cleared block!");
111
112 // The expression emitters assume (reasonably!) that the insertion
113 // point is always set. To maintain that, the call-emission code
114 // for noreturn functions has to enter a new block with no
115 // predecessors. We want to kill that block and mark the current
116 // insertion point unreachable in the common case of a call like
117 // "exit();". Since expression emission doesn't otherwise create
118 // blocks with no predecessors, we can just test for that.
119 // However, we must be careful not to do this to our incoming
120 // block, because *statement* emission does sometimes create
121 // reachable blocks which will have no predecessors until later in
122 // the function. This occurs with, e.g., labels that are not
123 // reachable by fallthrough.
124 if (incoming != outgoing && outgoing->use_empty()) {
125 outgoing->eraseFromParent();
126 Builder.ClearInsertionPoint();
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 }
128 break;
John McCallcd5b22e2011-01-12 03:41:02 +0000129 }
John McCall2a416372010-12-05 02:00:02 +0000130
Mike Stump1eb44332009-09-09 15:08:12 +0000131 case Stmt::IndirectGotoStmtClass:
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000132 EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000133
134 case Stmt::IfStmtClass: EmitIfStmt(cast<IfStmt>(*S)); break;
135 case Stmt::WhileStmtClass: EmitWhileStmt(cast<WhileStmt>(*S)); break;
136 case Stmt::DoStmtClass: EmitDoStmt(cast<DoStmt>(*S)); break;
137 case Stmt::ForStmtClass: EmitForStmt(cast<ForStmt>(*S)); break;
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 case Stmt::ReturnStmtClass: EmitReturnStmt(cast<ReturnStmt>(*S)); break;
Daniel Dunbara4275d12008-10-02 18:02:06 +0000140
Devang Patel51b09f22007-10-04 23:45:31 +0000141 case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
Chad Rosierd1a8d2e2012-08-28 21:11:24 +0000142 case Stmt::GCCAsmStmtClass: // Intentional fall-through.
143 case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800144 case Stmt::CoroutineBodyStmtClass:
145 case Stmt::CoreturnStmtClass:
146 CGM.ErrorUnsupported(S, "coroutine");
147 break;
Alexey Bataev0c018352013-09-06 18:03:48 +0000148 case Stmt::CapturedStmtClass: {
149 const CapturedStmt *CS = cast<CapturedStmt>(S);
150 EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
151 }
Tareq A. Siraj051303c2013-04-16 18:53:08 +0000152 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000153 case Stmt::ObjCAtTryStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000154 EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
Mike Stump1eb44332009-09-09 15:08:12 +0000155 break;
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000156 case Stmt::ObjCAtCatchStmtClass:
David Blaikieb219cfc2011-09-23 05:06:16 +0000157 llvm_unreachable(
158 "@catch statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000159 case Stmt::ObjCAtFinallyStmtClass:
David Blaikieb219cfc2011-09-23 05:06:16 +0000160 llvm_unreachable(
161 "@finally statements should be handled by EmitObjCAtTryStmt");
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000162 case Stmt::ObjCAtThrowStmtClass:
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000163 EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000164 break;
165 case Stmt::ObjCAtSynchronizedStmtClass:
Chris Lattner10cac6f2008-11-15 21:26:17 +0000166 EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000167 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000168 case Stmt::ObjCForCollectionStmtClass:
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000169 EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000170 break;
John McCallf85e1932011-06-15 23:02:42 +0000171 case Stmt::ObjCAutoreleasePoolStmtClass:
172 EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
173 break;
Chad Rosier6f61ba22012-06-20 17:43:05 +0000174
Anders Carlsson6815e942009-09-27 18:58:34 +0000175 case Stmt::CXXTryStmtClass:
176 EmitCXXTryStmt(cast<CXXTryStmt>(*S));
177 break;
Richard Smithad762fc2011-04-14 22:09:26 +0000178 case Stmt::CXXForRangeStmtClass:
179 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
Reid Kleckner98592d92013-09-16 21:46:30 +0000180 break;
John Wiegley28bbe4b2011-04-28 01:08:34 +0000181 case Stmt::SEHTryStmtClass:
Reid Kleckner98592d92013-09-16 21:46:30 +0000182 EmitSEHTryStmt(cast<SEHTryStmt>(*S));
Richard Smithad762fc2011-04-14 22:09:26 +0000183 break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700184 case Stmt::OMPParallelDirectiveClass:
185 EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
186 break;
187 case Stmt::OMPSimdDirectiveClass:
188 EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
189 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700190 case Stmt::OMPForDirectiveClass:
191 EmitOMPForDirective(cast<OMPForDirective>(*S));
192 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800193 case Stmt::OMPForSimdDirectiveClass:
194 EmitOMPForSimdDirective(cast<OMPForSimdDirective>(*S));
195 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700196 case Stmt::OMPSectionsDirectiveClass:
197 EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
198 break;
199 case Stmt::OMPSectionDirectiveClass:
200 EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
201 break;
202 case Stmt::OMPSingleDirectiveClass:
203 EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
204 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800205 case Stmt::OMPMasterDirectiveClass:
206 EmitOMPMasterDirective(cast<OMPMasterDirective>(*S));
207 break;
208 case Stmt::OMPCriticalDirectiveClass:
209 EmitOMPCriticalDirective(cast<OMPCriticalDirective>(*S));
210 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700211 case Stmt::OMPParallelForDirectiveClass:
212 EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
213 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800214 case Stmt::OMPParallelForSimdDirectiveClass:
215 EmitOMPParallelForSimdDirective(cast<OMPParallelForSimdDirective>(*S));
216 break;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700217 case Stmt::OMPParallelSectionsDirectiveClass:
218 EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
219 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800220 case Stmt::OMPTaskDirectiveClass:
221 EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
222 break;
223 case Stmt::OMPTaskyieldDirectiveClass:
224 EmitOMPTaskyieldDirective(cast<OMPTaskyieldDirective>(*S));
225 break;
226 case Stmt::OMPBarrierDirectiveClass:
227 EmitOMPBarrierDirective(cast<OMPBarrierDirective>(*S));
228 break;
229 case Stmt::OMPTaskwaitDirectiveClass:
230 EmitOMPTaskwaitDirective(cast<OMPTaskwaitDirective>(*S));
231 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800232 case Stmt::OMPTaskgroupDirectiveClass:
233 EmitOMPTaskgroupDirective(cast<OMPTaskgroupDirective>(*S));
234 break;
Stephen Hines176edba2014-12-01 14:53:08 -0800235 case Stmt::OMPFlushDirectiveClass:
236 EmitOMPFlushDirective(cast<OMPFlushDirective>(*S));
237 break;
238 case Stmt::OMPOrderedDirectiveClass:
239 EmitOMPOrderedDirective(cast<OMPOrderedDirective>(*S));
240 break;
241 case Stmt::OMPAtomicDirectiveClass:
242 EmitOMPAtomicDirective(cast<OMPAtomicDirective>(*S));
243 break;
244 case Stmt::OMPTargetDirectiveClass:
245 EmitOMPTargetDirective(cast<OMPTargetDirective>(*S));
246 break;
247 case Stmt::OMPTeamsDirectiveClass:
248 EmitOMPTeamsDirective(cast<OMPTeamsDirective>(*S));
249 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800250 case Stmt::OMPCancellationPointDirectiveClass:
251 EmitOMPCancellationPointDirective(cast<OMPCancellationPointDirective>(*S));
252 break;
253 case Stmt::OMPCancelDirectiveClass:
254 EmitOMPCancelDirective(cast<OMPCancelDirective>(*S));
255 break;
256 case Stmt::OMPTargetDataDirectiveClass:
257 EmitOMPTargetDataDirective(cast<OMPTargetDataDirective>(*S));
258 break;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700259 case Stmt::OMPTargetEnterDataDirectiveClass:
260 EmitOMPTargetEnterDataDirective(cast<OMPTargetEnterDataDirective>(*S));
261 break;
262 case Stmt::OMPTargetExitDataDirectiveClass:
263 EmitOMPTargetExitDataDirective(cast<OMPTargetExitDataDirective>(*S));
264 break;
265 case Stmt::OMPTargetParallelDirectiveClass:
266 EmitOMPTargetParallelDirective(cast<OMPTargetParallelDirective>(*S));
267 break;
268 case Stmt::OMPTargetParallelForDirectiveClass:
269 EmitOMPTargetParallelForDirective(cast<OMPTargetParallelForDirective>(*S));
270 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800271 case Stmt::OMPTaskLoopDirectiveClass:
272 EmitOMPTaskLoopDirective(cast<OMPTaskLoopDirective>(*S));
273 break;
274 case Stmt::OMPTaskLoopSimdDirectiveClass:
275 EmitOMPTaskLoopSimdDirective(cast<OMPTaskLoopSimdDirective>(*S));
276 break;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700277 case Stmt::OMPDistributeDirectiveClass:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800278 EmitOMPDistributeDirective(cast<OMPDistributeDirective>(*S));
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700279 break;
280 case Stmt::OMPTargetUpdateDirectiveClass:
281 EmitOMPTargetUpdateDirective(cast<OMPTargetUpdateDirective>(*S));
282 break;
283 case Stmt::OMPDistributeParallelForDirectiveClass:
284 EmitOMPDistributeParallelForDirective(
285 cast<OMPDistributeParallelForDirective>(*S));
286 break;
287 case Stmt::OMPDistributeParallelForSimdDirectiveClass:
288 EmitOMPDistributeParallelForSimdDirective(
289 cast<OMPDistributeParallelForSimdDirective>(*S));
290 break;
291 case Stmt::OMPDistributeSimdDirectiveClass:
292 EmitOMPDistributeSimdDirective(cast<OMPDistributeSimdDirective>(*S));
293 break;
294 case Stmt::OMPTargetParallelForSimdDirectiveClass:
295 EmitOMPTargetParallelForSimdDirective(
296 cast<OMPTargetParallelForSimdDirective>(*S));
297 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000298 }
299}
300
Daniel Dunbar09124252008-11-12 08:21:33 +0000301bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
302 switch (S->getStmtClass()) {
303 default: return false;
304 case Stmt::NullStmtClass: break;
305 case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
Daniel Dunbard286f052009-07-19 06:58:07 +0000306 case Stmt::DeclStmtClass: EmitDeclStmt(cast<DeclStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000307 case Stmt::LabelStmtClass: EmitLabelStmt(cast<LabelStmt>(*S)); break;
Richard Smith534986f2012-04-14 00:33:13 +0000308 case Stmt::AttributedStmtClass:
309 EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000310 case Stmt::GotoStmtClass: EmitGotoStmt(cast<GotoStmt>(*S)); break;
311 case Stmt::BreakStmtClass: EmitBreakStmt(cast<BreakStmt>(*S)); break;
312 case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
313 case Stmt::DefaultStmtClass: EmitDefaultStmt(cast<DefaultStmt>(*S)); break;
314 case Stmt::CaseStmtClass: EmitCaseStmt(cast<CaseStmt>(*S)); break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700315 case Stmt::SEHLeaveStmtClass: EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S)); break;
Daniel Dunbar09124252008-11-12 08:21:33 +0000316 }
317
318 return true;
319}
320
Chris Lattner33793202007-08-31 22:09:40 +0000321/// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true,
322/// this captures the expression result of the last sub-statement and returns it
323/// (for use by the statement expression extension).
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800324Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
325 AggValueSlot AggSlot) {
Chris Lattner7d22bf02009-03-05 08:04:57 +0000326 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
327 "LLVM IR generation of compound statement ('{}')");
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Eric Christopherfdc5d562012-02-23 00:43:07 +0000329 // Keep track of the current cleanup stack depth, including debug scopes.
330 LexicalScope Scope(*this, S.getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000331
David Blaikiea6504852013-01-26 22:16:26 +0000332 return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
333}
334
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800335Address
Eli Friedman2ac2fa72013-06-10 22:04:49 +0000336CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
337 bool GetLast,
338 AggValueSlot AggSlot) {
David Blaikiea6504852013-01-26 22:16:26 +0000339
Chris Lattner33793202007-08-31 22:09:40 +0000340 for (CompoundStmt::const_body_iterator I = S.body_begin(),
341 E = S.body_end()-GetLast; I != E; ++I)
Reid Spencer5f016e22007-07-11 17:01:13 +0000342 EmitStmt(*I);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000343
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800344 Address RetAlloca = Address::invalid();
Eli Friedman2ac2fa72013-06-10 22:04:49 +0000345 if (GetLast) {
Mike Stump1eb44332009-09-09 15:08:12 +0000346 // We have to special case labels here. They are statements, but when put
Anders Carlsson17d28a32008-12-12 05:52:00 +0000347 // at the end of a statement expression, they yield the value of their
348 // subexpression. Handle this by walking through all labels we encounter,
349 // emitting them before we evaluate the subexpr.
350 const Stmt *LastStmt = S.body_back();
351 while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000352 EmitLabel(LS->getDecl());
Anders Carlsson17d28a32008-12-12 05:52:00 +0000353 LastStmt = LS->getSubStmt();
354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Anders Carlsson17d28a32008-12-12 05:52:00 +0000356 EnsureInsertPoint();
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Eli Friedman2ac2fa72013-06-10 22:04:49 +0000358 QualType ExprTy = cast<Expr>(LastStmt)->getType();
359 if (hasAggregateEvaluationKind(ExprTy)) {
360 EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
361 } else {
362 // We can't return an RValue here because there might be cleanups at
363 // the end of the StmtExpr. Because of that, we have to emit the result
364 // here into a temporary alloca.
365 RetAlloca = CreateMemTemp(ExprTy);
366 EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
367 /*IsInit*/false);
368 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700369
Anders Carlsson17d28a32008-12-12 05:52:00 +0000370 }
371
Eli Friedman2ac2fa72013-06-10 22:04:49 +0000372 return RetAlloca;
Reid Spencer5f016e22007-07-11 17:01:13 +0000373}
374
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000375void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
376 llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000378 // If there is a cleanup stack, then we it isn't worth trying to
379 // simplify this block (we would need to remove it from the scope map
380 // and cleanup entry).
John McCallf1549f62010-07-06 01:34:17 +0000381 if (!EHStack.empty())
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000382 return;
383
384 // Can only simplify direct branches.
385 if (!BI || !BI->isUnconditional())
386 return;
387
Eli Friedman3d7c7802012-10-26 23:23:35 +0000388 // Can only simplify empty blocks.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800389 if (BI->getIterator() != BB->begin())
Eli Friedman3d7c7802012-10-26 23:23:35 +0000390 return;
391
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000392 BB->replaceAllUsesWith(BI->getSuccessor(0));
393 BI->eraseFromParent();
394 BB->eraseFromParent();
395}
396
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000397void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
John McCall548ce5e2010-04-21 11:18:06 +0000398 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
399
Daniel Dunbard57a8712008-11-11 09:41:28 +0000400 // Fall out of the current block (if necessary).
401 EmitBranch(BB);
Daniel Dunbara0c21a82008-11-13 01:24:05 +0000402
403 if (IsFinished && BB->use_empty()) {
404 delete BB;
405 return;
406 }
407
John McCall839cbaa2010-04-21 10:29:06 +0000408 // Place the block after the current block, if possible, or else at
409 // the end of the function.
John McCall548ce5e2010-04-21 11:18:06 +0000410 if (CurBB && CurBB->getParent())
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800411 CurFn->getBasicBlockList().insertAfter(CurBB->getIterator(), BB);
John McCall839cbaa2010-04-21 10:29:06 +0000412 else
413 CurFn->getBasicBlockList().push_back(BB);
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 Builder.SetInsertPoint(BB);
415}
416
Daniel Dunbard57a8712008-11-11 09:41:28 +0000417void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
418 // Emit a branch from the current block to the target one if this
419 // was a real block. If this was just a fall-through block after a
420 // terminator, don't emit it.
421 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
422
423 if (!CurBB || CurBB->getTerminator()) {
424 // If there is no insert point or the previous block is already
425 // terminated, don't touch it.
Daniel Dunbard57a8712008-11-11 09:41:28 +0000426 } else {
427 // Otherwise, create a fall-through branch.
428 Builder.CreateBr(Target);
429 }
Daniel Dunbar5e08ad32008-11-11 22:06:59 +0000430
431 Builder.ClearInsertionPoint();
Daniel Dunbard57a8712008-11-11 09:41:28 +0000432}
433
John McCall777d6e52011-08-11 02:22:43 +0000434void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
435 bool inserted = false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700436 for (llvm::User *u : block->users()) {
437 if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800438 CurFn->getBasicBlockList().insertAfter(insn->getParent()->getIterator(),
439 block);
John McCall777d6e52011-08-11 02:22:43 +0000440 inserted = true;
441 break;
442 }
443 }
444
445 if (!inserted)
446 CurFn->getBasicBlockList().push_back(block);
447
448 Builder.SetInsertPoint(block);
449}
450
John McCallf1549f62010-07-06 01:34:17 +0000451CodeGenFunction::JumpDest
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000452CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
453 JumpDest &Dest = LabelMap[D];
John McCallff8e1152010-07-23 21:56:41 +0000454 if (Dest.isValid()) return Dest;
John McCallf1549f62010-07-06 01:34:17 +0000455
456 // Create, but don't insert, the new block.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000457 Dest = JumpDest(createBasicBlock(D->getName()),
John McCallff8e1152010-07-23 21:56:41 +0000458 EHScopeStack::stable_iterator::invalid(),
459 NextCleanupDestIndex++);
John McCallf1549f62010-07-06 01:34:17 +0000460 return Dest;
461}
462
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000463void CodeGenFunction::EmitLabel(const LabelDecl *D) {
Nadav Rotem495cfa42013-03-23 06:43:35 +0000464 // Add this label to the current lexical scope if we're within any
465 // normal cleanups. Jumps "in" to this label --- when permitted by
466 // the language --- may need to be routed around such cleanups.
467 if (EHStack.hasNormalCleanups() && CurLexicalScope)
468 CurLexicalScope->addLabel(D);
469
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000470 JumpDest &Dest = LabelMap[D];
John McCallf1549f62010-07-06 01:34:17 +0000471
John McCallff8e1152010-07-23 21:56:41 +0000472 // If we didn't need a forward reference to this label, just go
John McCallf1549f62010-07-06 01:34:17 +0000473 // ahead and create a destination at the current scope.
John McCallff8e1152010-07-23 21:56:41 +0000474 if (!Dest.isValid()) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000475 Dest = getJumpDestInCurrentScope(D->getName());
John McCallf1549f62010-07-06 01:34:17 +0000476
477 // Otherwise, we need to give this label a target depth and remove
478 // it from the branch-fixups list.
479 } else {
John McCallff8e1152010-07-23 21:56:41 +0000480 assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
Nadav Rotem495cfa42013-03-23 06:43:35 +0000481 Dest.setScopeDepth(EHStack.stable_begin());
John McCallff8e1152010-07-23 21:56:41 +0000482 ResolveBranchFixups(Dest.getBlock());
John McCallf1549f62010-07-06 01:34:17 +0000483 }
484
John McCallff8e1152010-07-23 21:56:41 +0000485 EmitBlock(Dest.getBlock());
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700486 incrementProfileCounter(D->getStmt());
Chris Lattner91d723d2008-07-26 20:23:23 +0000487}
488
Nadav Rotem495cfa42013-03-23 06:43:35 +0000489/// Change the cleanup scope of the labels in this lexical scope to
490/// match the scope of the enclosing context.
491void CodeGenFunction::LexicalScope::rescopeLabels() {
492 assert(!Labels.empty());
493 EHScopeStack::stable_iterator innermostScope
494 = CGF.EHStack.getInnermostNormalCleanup();
495
496 // Change the scope depth of all the labels.
497 for (SmallVectorImpl<const LabelDecl*>::const_iterator
498 i = Labels.begin(), e = Labels.end(); i != e; ++i) {
499 assert(CGF.LabelMap.count(*i));
500 JumpDest &dest = CGF.LabelMap.find(*i)->second;
501 assert(dest.getScopeDepth().isValid());
502 assert(innermostScope.encloses(dest.getScopeDepth()));
503 dest.setScopeDepth(innermostScope);
504 }
505
506 // Reparent the labels if the new scope also has cleanups.
507 if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
508 ParentScope->Labels.append(Labels.begin(), Labels.end());
509 }
510}
511
Chris Lattner91d723d2008-07-26 20:23:23 +0000512
513void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000514 EmitLabel(S.getDecl());
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 EmitStmt(S.getSubStmt());
516}
517
Richard Smith534986f2012-04-14 00:33:13 +0000518void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700519 const Stmt *SubStmt = S.getSubStmt();
520 switch (SubStmt->getStmtClass()) {
521 case Stmt::DoStmtClass:
522 EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
523 break;
524 case Stmt::ForStmtClass:
525 EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
526 break;
527 case Stmt::WhileStmtClass:
528 EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
529 break;
530 case Stmt::CXXForRangeStmtClass:
531 EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
532 break;
533 default:
534 EmitStmt(SubStmt);
535 }
Richard Smith534986f2012-04-14 00:33:13 +0000536}
537
Reid Spencer5f016e22007-07-11 17:01:13 +0000538void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
Daniel Dunbar09124252008-11-12 08:21:33 +0000539 // If this code is reachable then emit a stop point (if generating
540 // debug info). We have to do this ourselves because we are on the
541 // "simple" statement path.
542 if (HaveInsertPoint())
543 EmitStopPoint(&S);
Mike Stump36a2ada2009-02-07 12:52:26 +0000544
John McCallf1549f62010-07-06 01:34:17 +0000545 EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000546}
547
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000548
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000549void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000550 if (const LabelDecl *Target = S.getConstantTarget()) {
John McCall95c225d2010-10-28 08:53:48 +0000551 EmitBranchThroughCleanup(getJumpDestForLabel(Target));
552 return;
553 }
554
Chris Lattner49c952f2009-11-06 18:10:47 +0000555 // Ensure that we have an i8* for our PHI node.
Chris Lattnerd9becd12009-10-28 23:59:40 +0000556 llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
John McCalld16c2cf2011-02-08 08:22:06 +0000557 Int8PtrTy, "addr");
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000558 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000559
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000560 // Get the basic block for the indirect goto.
561 llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
Chad Rosier6f61ba22012-06-20 17:43:05 +0000562
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000563 // The first instruction in the block has to be the PHI for the switch dest,
564 // add an entry for this branch.
565 cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
Chad Rosier6f61ba22012-06-20 17:43:05 +0000566
Chris Lattner3d00fdc2009-10-13 06:55:33 +0000567 EmitBranch(IndGotoBB);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000568}
569
Chris Lattner62b72f62008-11-11 07:24:28 +0000570void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 // C99 6.8.4.1: The first substatement is executed if the expression compares
572 // unequal to 0. The condition must be a scalar type.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700573 LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
Adrian Prantl8d378582013-06-08 00:16:55 +0000574
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700575 if (S.getInit())
576 EmitStmt(S.getInit());
577
Douglas Gregor8cfe5a72009-11-23 23:44:04 +0000578 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000579 EmitAutoVarDecl(*S.getConditionVariable());
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Chris Lattner9bc47e22008-11-12 07:46:33 +0000581 // If the condition constant folds and can be elided, try to avoid emitting
582 // the condition and the dead arm of the if/else.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000583 bool CondConstant;
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700584 if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant,
585 S.isConstexpr())) {
Chris Lattner62b72f62008-11-11 07:24:28 +0000586 // Figure out which block (then or else) is executed.
Chris Lattnerc2c90012011-02-27 23:02:32 +0000587 const Stmt *Executed = S.getThen();
588 const Stmt *Skipped = S.getElse();
589 if (!CondConstant) // Condition false?
Chris Lattner62b72f62008-11-11 07:24:28 +0000590 std::swap(Executed, Skipped);
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner62b72f62008-11-11 07:24:28 +0000592 // If the skipped block has no labels in it, just emit the executed block.
593 // This avoids emitting dead code and simplifies the CFG substantially.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700594 if (S.isConstexpr() || !ContainsLabel(Skipped)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700595 if (CondConstant)
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700596 incrementProfileCounter(&S);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000597 if (Executed) {
John McCallf1549f62010-07-06 01:34:17 +0000598 RunCleanupsScope ExecutedScope(*this);
Chris Lattner62b72f62008-11-11 07:24:28 +0000599 EmitStmt(Executed);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000600 }
Chris Lattner62b72f62008-11-11 07:24:28 +0000601 return;
602 }
603 }
Chris Lattner9bc47e22008-11-12 07:46:33 +0000604
605 // Otherwise, the condition did not fold, or we couldn't elide it. Just emit
606 // the conditional branch.
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000607 llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
608 llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
609 llvm::BasicBlock *ElseBlock = ContBlock;
Reid Spencer5f016e22007-07-11 17:01:13 +0000610 if (S.getElse())
Daniel Dunbar781d7ca2008-11-13 00:47:57 +0000611 ElseBlock = createBasicBlock("if.else");
Stephen Hines651f13c2014-04-23 16:59:28 -0700612
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700613 EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock,
614 getProfileCount(S.getThen()));
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616 // Emit the 'then' code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700617 EmitBlock(ThenBlock);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700618 incrementProfileCounter(&S);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000619 {
John McCallf1549f62010-07-06 01:34:17 +0000620 RunCleanupsScope ThenScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000621 EmitStmt(S.getThen());
622 }
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700623 {
624 auto CurBlock = Builder.GetInsertBlock();
625 EmitBranch(ContBlock);
626 // Eliminate any empty blocks that may have been created by nested
627 // control flow statements in the 'then' clause.
628 if (CurBlock)
629 SimplifyForwardingBlocks(CurBlock);
630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 // Emit the 'else' code if present.
633 if (const Stmt *Else = S.getElse()) {
Stephen Hines176edba2014-12-01 14:53:08 -0800634 {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700635 // There is no need to emit line number for an unconditional branch.
636 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Stephen Hines176edba2014-12-01 14:53:08 -0800637 EmitBlock(ElseBlock);
638 }
Douglas Gregor01234bb2009-11-24 16:43:22 +0000639 {
John McCallf1549f62010-07-06 01:34:17 +0000640 RunCleanupsScope ElseScope(*this);
Douglas Gregor01234bb2009-11-24 16:43:22 +0000641 EmitStmt(Else);
642 }
Stephen Hines176edba2014-12-01 14:53:08 -0800643 {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700644 // There is no need to emit line number for an unconditional branch.
645 auto NL = ApplyDebugLocation::CreateEmpty(*this);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700646 auto CurBlock = Builder.GetInsertBlock();
Stephen Hines176edba2014-12-01 14:53:08 -0800647 EmitBranch(ContBlock);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700648 // Eliminate any empty blocks that may have been created by nested
649 // control flow statements emitted in the 'else' clause.
650 if (CurBlock)
651 SimplifyForwardingBlocks(CurBlock);
Stephen Hines176edba2014-12-01 14:53:08 -0800652 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 }
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Reid Spencer5f016e22007-07-11 17:01:13 +0000655 // Emit the continuation block for code after the if.
Daniel Dunbarc22d6652008-11-13 01:54:24 +0000656 EmitBlock(ContBlock, true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000657}
658
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700659void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
Stephen Hines176edba2014-12-01 14:53:08 -0800660 ArrayRef<const Attr *> WhileAttrs) {
John McCallf1549f62010-07-06 01:34:17 +0000661 // Emit the header for the loop, which will also become
662 // the continue target.
663 JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
John McCallff8e1152010-07-23 21:56:41 +0000664 EmitBlock(LoopHeader.getBlock());
Mike Stump72cac2c2009-02-07 18:08:12 +0000665
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700666 LoopStack.push(LoopHeader.getBlock(), CGM.getContext(), WhileAttrs,
667 Builder.getCurrentDebugLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700668
John McCallf1549f62010-07-06 01:34:17 +0000669 // Create an exit block for when the condition fails, which will
670 // also become the break target.
671 JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
Mike Stump72cac2c2009-02-07 18:08:12 +0000672
673 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000674 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Douglas Gregor5656e142009-11-24 21:15:44 +0000676 // C++ [stmt.while]p2:
677 // When the condition of a while statement is a declaration, the
678 // scope of the variable that is declared extends from its point
679 // of declaration (3.3.2) to the end of the while statement.
680 // [...]
681 // The object created in a condition is destroyed and created
682 // with each iteration of the loop.
John McCallf1549f62010-07-06 01:34:17 +0000683 RunCleanupsScope ConditionScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000684
John McCallf1549f62010-07-06 01:34:17 +0000685 if (S.getConditionVariable())
John McCallb6bbcc92010-10-15 04:57:14 +0000686 EmitAutoVarDecl(*S.getConditionVariable());
Chad Rosier6f61ba22012-06-20 17:43:05 +0000687
Mike Stump16b16202009-02-07 17:18:33 +0000688 // Evaluate the conditional in the while header. C99 6.8.5.1: The
689 // evaluation of the controlling expression takes place before each
690 // execution of the loop body.
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Chad Rosier6f61ba22012-06-20 17:43:05 +0000692
Devang Patel2c30d8f2007-10-09 20:51:27 +0000693 // while(1) is common, avoid extra exit blocks. Be sure
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 // to correctly handle break/continue though.
Devang Patel2c30d8f2007-10-09 20:51:27 +0000695 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000696 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel2c30d8f2007-10-09 20:51:27 +0000697 if (C->isOne())
698 EmitBoolCondBranch = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 // As long as the condition is true, go to the loop body.
John McCallf1549f62010-07-06 01:34:17 +0000701 llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
702 if (EmitBoolCondBranch) {
John McCallff8e1152010-07-23 21:56:41 +0000703 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
John McCallf1549f62010-07-06 01:34:17 +0000704 if (ConditionScope.requiresCleanups())
705 ExitBlock = createBasicBlock("while.exit");
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800706 Builder.CreateCondBr(
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700707 BoolCondVal, LoopBody, ExitBlock,
708 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
John McCallf1549f62010-07-06 01:34:17 +0000709
John McCallff8e1152010-07-23 21:56:41 +0000710 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000711 EmitBlock(ExitBlock);
712 EmitBranchThroughCleanup(LoopExit);
713 }
714 }
Chad Rosier6f61ba22012-06-20 17:43:05 +0000715
John McCallf1549f62010-07-06 01:34:17 +0000716 // Emit the loop body. We have to emit this in a cleanup scope
717 // because it might be a singleton DeclStmt.
Douglas Gregor5656e142009-11-24 21:15:44 +0000718 {
John McCallf1549f62010-07-06 01:34:17 +0000719 RunCleanupsScope BodyScope(*this);
Douglas Gregor5656e142009-11-24 21:15:44 +0000720 EmitBlock(LoopBody);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700721 incrementProfileCounter(&S);
Douglas Gregor5656e142009-11-24 21:15:44 +0000722 EmitStmt(S.getBody());
723 }
Chris Lattnerda138702007-07-16 21:28:45 +0000724
Mike Stump1eb44332009-09-09 15:08:12 +0000725 BreakContinueStack.pop_back();
726
John McCallf1549f62010-07-06 01:34:17 +0000727 // Immediately force cleanup.
728 ConditionScope.ForceCleanup();
Douglas Gregor5656e142009-11-24 21:15:44 +0000729
Stephen Hines176edba2014-12-01 14:53:08 -0800730 EmitStopPoint(&S);
John McCallf1549f62010-07-06 01:34:17 +0000731 // Branch to the loop header again.
John McCallff8e1152010-07-23 21:56:41 +0000732 EmitBranch(LoopHeader.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700734 LoopStack.pop();
735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000737 EmitBlock(LoopExit.getBlock(), true);
Douglas Gregor5656e142009-11-24 21:15:44 +0000738
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000739 // The LoopHeader typically is just a branch if we skipped emitting
740 // a branch, try to erase it.
John McCallf1549f62010-07-06 01:34:17 +0000741 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000742 SimplifyForwardingBlocks(LoopHeader.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000743}
744
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700745void CodeGenFunction::EmitDoStmt(const DoStmt &S,
Stephen Hines176edba2014-12-01 14:53:08 -0800746 ArrayRef<const Attr *> DoAttrs) {
John McCallf1549f62010-07-06 01:34:17 +0000747 JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
748 JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700750 uint64_t ParentCount = getCurrentProfileCount();
Stephen Hines651f13c2014-04-23 16:59:28 -0700751
Chris Lattnerda138702007-07-16 21:28:45 +0000752 // Store the blocks to use for break and continue.
John McCallf1549f62010-07-06 01:34:17 +0000753 BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
Mike Stump1eb44332009-09-09 15:08:12 +0000754
John McCallf1549f62010-07-06 01:34:17 +0000755 // Emit the body of the loop.
756 llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700757
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700758 LoopStack.push(LoopBody, CGM.getContext(), DoAttrs,
759 Builder.getCurrentDebugLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700760
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700761 EmitBlockWithFallThrough(LoopBody, &S);
John McCallf1549f62010-07-06 01:34:17 +0000762 {
763 RunCleanupsScope BodyScope(*this);
764 EmitStmt(S.getBody());
765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
John McCallff8e1152010-07-23 21:56:41 +0000767 EmitBlock(LoopCond.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 // C99 6.8.5.2: "The evaluation of the controlling expression takes place
770 // after each execution of the loop body."
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Reid Spencer5f016e22007-07-11 17:01:13 +0000772 // Evaluate the conditional in the while header.
773 // C99 6.8.5p2/p4: The first substatement is executed if the expression
774 // compares unequal to 0. The condition must be a scalar type.
775 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000776
Stephen Hines651f13c2014-04-23 16:59:28 -0700777 BreakContinueStack.pop_back();
778
Devang Patel05f6e6b2007-10-09 20:33:39 +0000779 // "do {} while (0)" is common in macros, avoid extra blocks. Be sure
780 // to correctly handle break/continue though.
781 bool EmitBoolCondBranch = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000782 if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
Devang Patel05f6e6b2007-10-09 20:33:39 +0000783 if (C->isZero())
784 EmitBoolCondBranch = false;
785
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 // As long as the condition is true, iterate the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700787 if (EmitBoolCondBranch) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700788 uint64_t BackedgeCount = getProfileCount(S.getBody()) - ParentCount;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800789 Builder.CreateCondBr(
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700790 BoolCondVal, LoopBody, LoopExit.getBlock(),
791 createProfileWeightsForLoop(S.getCond(), BackedgeCount));
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700794 LoopStack.pop();
795
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 // Emit the exit block.
John McCallff8e1152010-07-23 21:56:41 +0000797 EmitBlock(LoopExit.getBlock());
Devang Patel05f6e6b2007-10-09 20:33:39 +0000798
Daniel Dunbaraa5bd872009-04-01 04:37:47 +0000799 // The DoCond block typically is just a branch if we skipped
800 // emitting a branch, try to erase it.
801 if (!EmitBoolCondBranch)
John McCallff8e1152010-07-23 21:56:41 +0000802 SimplifyForwardingBlocks(LoopCond.getBlock());
Reid Spencer5f016e22007-07-11 17:01:13 +0000803}
804
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700805void CodeGenFunction::EmitForStmt(const ForStmt &S,
Stephen Hines176edba2014-12-01 14:53:08 -0800806 ArrayRef<const Attr *> ForAttrs) {
John McCallf1549f62010-07-06 01:34:17 +0000807 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
808
Stephen Hines176edba2014-12-01 14:53:08 -0800809 LexicalScope ForScope(*this, S.getSourceRange());
Devang Patel0554e0e2010-08-25 00:28:56 +0000810
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700811 llvm::DebugLoc DL = Builder.getCurrentDebugLocation();
812
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 // Evaluate the first part before the loop.
814 if (S.getInit())
815 EmitStmt(S.getInit());
816
817 // Start the loop with a block that tests the condition.
John McCallf1549f62010-07-06 01:34:17 +0000818 // If there's an increment, the continue scope will be overwritten
819 // later.
820 JumpDest Continue = getJumpDestInCurrentScope("for.cond");
John McCallff8e1152010-07-23 21:56:41 +0000821 llvm::BasicBlock *CondBlock = Continue.getBlock();
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 EmitBlock(CondBlock);
823
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700824 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs, DL);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700825
Stephen Hines651f13c2014-04-23 16:59:28 -0700826 // If the for loop doesn't have an increment we can just use the
827 // condition as the continue block. Otherwise we'll need to create
828 // a block for it (in the current scope, i.e. in the scope of the
829 // condition), and that we will become our continue block.
830 if (S.getInc())
831 Continue = getJumpDestInCurrentScope("for.inc");
832
833 // Store the blocks to use for break and continue.
834 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
835
Douglas Gregord9752062009-11-25 01:51:31 +0000836 // Create a cleanup scope for the condition variable cleanups.
Stephen Hines176edba2014-12-01 14:53:08 -0800837 LexicalScope ConditionScope(*this, S.getSourceRange());
Chad Rosier6f61ba22012-06-20 17:43:05 +0000838
Reid Spencer5f016e22007-07-11 17:01:13 +0000839 if (S.getCond()) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +0000840 // If the for statement has a condition scope, emit the local variable
841 // declaration.
Douglas Gregord9752062009-11-25 01:51:31 +0000842 if (S.getConditionVariable()) {
John McCallb6bbcc92010-10-15 04:57:14 +0000843 EmitAutoVarDecl(*S.getConditionVariable());
Douglas Gregord9752062009-11-25 01:51:31 +0000844 }
John McCallf1549f62010-07-06 01:34:17 +0000845
Justin Bognerfd93e4a2013-11-04 16:13:18 +0000846 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
John McCallf1549f62010-07-06 01:34:17 +0000847 // If there are any cleanups between here and the loop-exit scope,
848 // create a block to stage a loop exit along.
849 if (ForScope.requiresCleanups())
850 ExitBlock = createBasicBlock("for.cond.cleanup");
Chad Rosier6f61ba22012-06-20 17:43:05 +0000851
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 // As long as the condition is true, iterate the loop.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000853 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner31a09842008-11-12 08:04:58 +0000855 // C99 6.8.5p2/p4: The first substatement is executed if the expression
856 // compares unequal to 0. The condition must be a scalar type.
Stephen Hines651f13c2014-04-23 16:59:28 -0700857 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800858 Builder.CreateCondBr(
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700859 BoolCondVal, ForBody, ExitBlock,
860 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700861
John McCallff8e1152010-07-23 21:56:41 +0000862 if (ExitBlock != LoopExit.getBlock()) {
John McCallf1549f62010-07-06 01:34:17 +0000863 EmitBlock(ExitBlock);
864 EmitBranchThroughCleanup(LoopExit);
865 }
Mike Stump1eb44332009-09-09 15:08:12 +0000866
867 EmitBlock(ForBody);
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 } else {
869 // Treat it as a non-zero constant. Don't even create a new block for the
870 // body, just fall into it.
871 }
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700872 incrementProfileCounter(&S);
Mike Stump3e9da662009-02-07 23:02:10 +0000873
Douglas Gregord9752062009-11-25 01:51:31 +0000874 {
875 // Create a separate cleanup scope for the body, in case it is not
876 // a compound statement.
John McCallf1549f62010-07-06 01:34:17 +0000877 RunCleanupsScope BodyScope(*this);
Douglas Gregord9752062009-11-25 01:51:31 +0000878 EmitStmt(S.getBody());
879 }
Chris Lattnerda138702007-07-16 21:28:45 +0000880
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 // If there is an increment, emit it next.
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000882 if (S.getInc()) {
John McCallff8e1152010-07-23 21:56:41 +0000883 EmitBlock(Continue.getBlock());
Chris Lattner883f6a72007-08-11 00:04:45 +0000884 EmitStmt(S.getInc());
Daniel Dunbarad12b6d2008-09-28 00:19:22 +0000885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Douglas Gregor45d3fe12010-05-21 18:36:48 +0000887 BreakContinueStack.pop_back();
Douglas Gregord9752062009-11-25 01:51:31 +0000888
John McCallf1549f62010-07-06 01:34:17 +0000889 ConditionScope.ForceCleanup();
Stephen Hines176edba2014-12-01 14:53:08 -0800890
891 EmitStopPoint(&S);
John McCallf1549f62010-07-06 01:34:17 +0000892 EmitBranch(CondBlock);
893
894 ForScope.ForceCleanup();
895
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700896 LoopStack.pop();
897
Chris Lattnerda138702007-07-16 21:28:45 +0000898 // Emit the fall-through block.
John McCallff8e1152010-07-23 21:56:41 +0000899 EmitBlock(LoopExit.getBlock(), true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000900}
901
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700902void
903CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
Stephen Hines176edba2014-12-01 14:53:08 -0800904 ArrayRef<const Attr *> ForAttrs) {
Richard Smithad762fc2011-04-14 22:09:26 +0000905 JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
906
Stephen Hines176edba2014-12-01 14:53:08 -0800907 LexicalScope ForScope(*this, S.getSourceRange());
Richard Smithad762fc2011-04-14 22:09:26 +0000908
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700909 llvm::DebugLoc DL = Builder.getCurrentDebugLocation();
910
Richard Smithad762fc2011-04-14 22:09:26 +0000911 // Evaluate the first pieces before the loop.
912 EmitStmt(S.getRangeStmt());
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700913 EmitStmt(S.getBeginStmt());
914 EmitStmt(S.getEndStmt());
Richard Smithad762fc2011-04-14 22:09:26 +0000915
916 // Start the loop with a block that tests the condition.
917 // If there's an increment, the continue scope will be overwritten
918 // later.
919 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
920 EmitBlock(CondBlock);
921
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -0700922 LoopStack.push(CondBlock, CGM.getContext(), ForAttrs, DL);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700923
Richard Smithad762fc2011-04-14 22:09:26 +0000924 // If there are any cleanups between here and the loop-exit scope,
925 // create a block to stage a loop exit along.
926 llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
927 if (ForScope.requiresCleanups())
928 ExitBlock = createBasicBlock("for.cond.cleanup");
Chad Rosier6f61ba22012-06-20 17:43:05 +0000929
Richard Smithad762fc2011-04-14 22:09:26 +0000930 // The loop body, consisting of the specified body and the loop variable.
931 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
932
933 // The body is executed if the expression, contextually converted
934 // to bool, is true.
Stephen Hines651f13c2014-04-23 16:59:28 -0700935 llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800936 Builder.CreateCondBr(
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700937 BoolCondVal, ForBody, ExitBlock,
938 createProfileWeightsForLoop(S.getCond(), getProfileCount(S.getBody())));
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700939
Richard Smithad762fc2011-04-14 22:09:26 +0000940 if (ExitBlock != LoopExit.getBlock()) {
941 EmitBlock(ExitBlock);
942 EmitBranchThroughCleanup(LoopExit);
943 }
944
945 EmitBlock(ForBody);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -0700946 incrementProfileCounter(&S);
Richard Smithad762fc2011-04-14 22:09:26 +0000947
948 // Create a block for the increment. In case of a 'continue', we jump there.
949 JumpDest Continue = getJumpDestInCurrentScope("for.inc");
950
951 // Store the blocks to use for break and continue.
952 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
953
954 {
955 // Create a separate cleanup scope for the loop variable and body.
Stephen Hines176edba2014-12-01 14:53:08 -0800956 LexicalScope BodyScope(*this, S.getSourceRange());
Richard Smithad762fc2011-04-14 22:09:26 +0000957 EmitStmt(S.getLoopVarStmt());
958 EmitStmt(S.getBody());
959 }
960
Stephen Hines176edba2014-12-01 14:53:08 -0800961 EmitStopPoint(&S);
Richard Smithad762fc2011-04-14 22:09:26 +0000962 // If there is an increment, emit it next.
963 EmitBlock(Continue.getBlock());
964 EmitStmt(S.getInc());
965
966 BreakContinueStack.pop_back();
967
968 EmitBranch(CondBlock);
969
970 ForScope.ForceCleanup();
971
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700972 LoopStack.pop();
973
Richard Smithad762fc2011-04-14 22:09:26 +0000974 // Emit the fall-through block.
975 EmitBlock(LoopExit.getBlock(), true);
976}
977
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000978void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
979 if (RV.isScalar()) {
980 Builder.CreateStore(RV.getScalarVal(), ReturnValue);
981 } else if (RV.isAggregate()) {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800982 EmitAggregateCopy(ReturnValue, RV.getAggregateAddress(), Ty);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000983 } else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -0800984 EmitStoreOfComplex(RV.getComplexVal(), MakeAddrLValue(ReturnValue, Ty),
John McCall9d232c82013-03-07 21:37:08 +0000985 /*init*/ true);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000986 }
Anders Carlsson82d8ef02009-02-09 20:31:03 +0000987 EmitBranchThroughCleanup(ReturnBlock);
Daniel Dunbar29e0bcc2008-09-24 04:00:38 +0000988}
989
Reid Spencer5f016e22007-07-11 17:01:13 +0000990/// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
991/// if the function returns void, or may be missing one if the function returns
992/// non-void. Fun stuff :).
993void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700994 // Returning from an outlined SEH helper is UB, and we already warn on it.
995 if (IsOutlinedSEHHelper) {
996 Builder.CreateUnreachable();
997 Builder.ClearInsertionPoint();
998 }
999
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 // Emit the result value, even if unused, to evalute the side effects.
1001 const Expr *RV = S.getRetValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001002
John McCall9f357de2012-09-25 06:56:03 +00001003 // Treat block literals in a return expression as if they appeared
1004 // in their own scope. This permits a small, easily-implemented
1005 // exception to our over-conservative rules about not jumping to
1006 // statements following block literals with non-trivial cleanups.
1007 RunCleanupsScope cleanupScope(*this);
1008 if (const ExprWithCleanups *cleanups =
1009 dyn_cast_or_null<ExprWithCleanups>(RV)) {
1010 enterFullExpression(cleanups);
1011 RV = cleanups->getSubExpr();
1012 }
1013
Daniel Dunbar5ca20842008-09-09 21:00:17 +00001014 // FIXME: Clean this up by using an LValue for ReturnTemp,
1015 // EmitStoreThroughLValue, and EmitAnyExpr.
Stephen Hines651f13c2014-04-23 16:59:28 -07001016 if (getLangOpts().ElideConstructors &&
1017 S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
Douglas Gregord86c4772010-05-15 06:46:45 +00001018 // Apply the named return value optimization for this return statement,
1019 // which means doing nothing: the appropriate result has already been
1020 // constructed into the NRVO variable.
Chad Rosier6f61ba22012-06-20 17:43:05 +00001021
Douglas Gregor3d91bbc2010-05-17 15:52:46 +00001022 // If there is an NRVO flag for this variable, set it to 1 into indicate
1023 // that the cleanup code should not destroy the variable.
John McCalld16c2cf2011-02-08 08:22:06 +00001024 if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001025 Builder.CreateFlagStore(Builder.getTrue(), NRVOFlag);
1026 } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +00001027 // Make sure not to return anything, but evaluate the expression
1028 // for side effects.
1029 if (RV)
Eli Friedman144ac612008-05-22 01:22:33 +00001030 EmitAnyExpr(RV);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001031 } else if (!RV) {
Daniel Dunbar5ca20842008-09-09 21:00:17 +00001032 // Do nothing (return value is left uninitialized)
Eli Friedmand54b6ac2009-05-27 04:56:12 +00001033 } else if (FnRetTy->isReferenceType()) {
1034 // If this function returns a reference, take the address of the expression
1035 // rather than the value.
Richard Smithd4ec5622013-06-12 23:38:09 +00001036 RValue Result = EmitReferenceBindingToExpr(RV);
Douglas Gregor33fd1fc2010-03-24 23:14:04 +00001037 Builder.CreateStore(Result.getScalarVal(), ReturnValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 } else {
John McCall9d232c82013-03-07 21:37:08 +00001039 switch (getEvaluationKind(RV->getType())) {
1040 case TEK_Scalar:
1041 Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1042 break;
1043 case TEK_Complex:
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001044 EmitComplexExprIntoLValue(RV, MakeAddrLValue(ReturnValue, RV->getType()),
John McCall9d232c82013-03-07 21:37:08 +00001045 /*isInit*/ true);
1046 break;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001047 case TEK_Aggregate:
1048 EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue,
John McCall9d232c82013-03-07 21:37:08 +00001049 Qualifiers(),
1050 AggValueSlot::IsDestructed,
1051 AggValueSlot::DoesNotNeedGCBarriers,
1052 AggValueSlot::IsNotAliased));
1053 break;
1054 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 }
Eli Friedman144ac612008-05-22 01:22:33 +00001056
Adrian Prantlddb379e2013-05-07 22:41:09 +00001057 ++NumReturnExprs;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001058 if (!RV || RV->isEvaluatable(getContext()))
Adrian Prantlddb379e2013-05-07 22:41:09 +00001059 ++NumSimpleReturnExprs;
Adrian Prantlfa6b0792013-05-02 17:30:20 +00001060
John McCall9f357de2012-09-25 06:56:03 +00001061 cleanupScope.ForceCleanup();
Anders Carlsson82d8ef02009-02-09 20:31:03 +00001062 EmitBranchThroughCleanup(ReturnBlock);
Reid Spencer5f016e22007-07-11 17:01:13 +00001063}
1064
1065void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
Devang Patel91981262011-06-04 00:38:02 +00001066 // As long as debug info is modeled with instructions, we have to ensure we
1067 // have a place to insert here and write the stop point here.
Eric Christopher2b124ea2012-04-10 05:04:07 +00001068 if (HaveInsertPoint())
Devang Patel91981262011-06-04 00:38:02 +00001069 EmitStopPoint(&S);
1070
Stephen Hines651f13c2014-04-23 16:59:28 -07001071 for (const auto *I : S.decls())
1072 EmitDecl(*I);
Chris Lattner6fa5f092007-07-12 15:43:07 +00001073}
Chris Lattnerda138702007-07-16 21:28:45 +00001074
Daniel Dunbar09124252008-11-12 08:21:33 +00001075void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +00001076 assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1077
Daniel Dunbar09124252008-11-12 08:21:33 +00001078 // If this code is reachable then emit a stop point (if generating
1079 // debug info). We have to do this ourselves because we are on the
1080 // "simple" statement path.
1081 if (HaveInsertPoint())
1082 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +00001083
Stephen Hines651f13c2014-04-23 16:59:28 -07001084 EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
Chris Lattnerda138702007-07-16 21:28:45 +00001085}
1086
Daniel Dunbar09124252008-11-12 08:21:33 +00001087void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
Chris Lattnerda138702007-07-16 21:28:45 +00001088 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1089
Daniel Dunbar09124252008-11-12 08:21:33 +00001090 // If this code is reachable then emit a stop point (if generating
1091 // debug info). We have to do this ourselves because we are on the
1092 // "simple" statement path.
1093 if (HaveInsertPoint())
1094 EmitStopPoint(&S);
Mike Stumpec9771d2009-02-08 09:22:19 +00001095
Stephen Hines651f13c2014-04-23 16:59:28 -07001096 EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
Chris Lattnerda138702007-07-16 21:28:45 +00001097}
Devang Patel51b09f22007-10-04 23:45:31 +00001098
Devang Patelc049e4f2007-10-08 20:57:48 +00001099/// EmitCaseStmtRange - If case statement range is not too big then
1100/// add multiple cases to switch instruction, one for each value within
1101/// the range. If range is too big then emit "if" condition check.
1102void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
Daniel Dunbar4efde8d2008-07-24 01:18:41 +00001103 assert(S.getRHS() && "Expected RHS value in CaseStmt");
Devang Patelc049e4f2007-10-08 20:57:48 +00001104
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001105 llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1106 llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
Daniel Dunbar4efde8d2008-07-24 01:18:41 +00001107
Daniel Dunbar16f23572008-07-25 01:11:38 +00001108 // Emit the code for this case. We do this first to make sure it is
1109 // properly chained from our predecessor before generating the
1110 // switch machinery to enter this block.
Stephen Hines651f13c2014-04-23 16:59:28 -07001111 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001112 EmitBlockWithFallThrough(CaseDest, &S);
Daniel Dunbar16f23572008-07-25 01:11:38 +00001113 EmitStmt(S.getSubStmt());
1114
Daniel Dunbar4efde8d2008-07-24 01:18:41 +00001115 // If range is empty, do nothing.
1116 if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1117 return;
Devang Patelc049e4f2007-10-08 20:57:48 +00001118
1119 llvm::APInt Range = RHS - LHS;
Daniel Dunbar16f23572008-07-25 01:11:38 +00001120 // FIXME: parameters such as this should not be hardcoded.
Devang Patelc049e4f2007-10-08 20:57:48 +00001121 if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1122 // Range is small enough to add multiple switch instruction cases.
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001123 uint64_t Total = getProfileCount(&S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001124 unsigned NCases = Range.getZExtValue() + 1;
1125 // We only have one region counter for the entire set of cases here, so we
1126 // need to divide the weights evenly between the generated cases, ensuring
1127 // that the total weight is preserved. E.g., a weight of 5 over three cases
1128 // will be distributed as weights of 2, 2, and 1.
1129 uint64_t Weight = Total / NCases, Rem = Total % NCases;
1130 for (unsigned I = 0; I != NCases; ++I) {
1131 if (SwitchWeights)
1132 SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1133 if (Rem)
1134 Rem--;
Chris Lattner97d54372011-04-19 20:53:45 +00001135 SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
Devang Patel2d79d0f2007-10-05 20:54:07 +00001136 LHS++;
1137 }
Devang Patelc049e4f2007-10-08 20:57:48 +00001138 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001139 }
1140
Daniel Dunbar16f23572008-07-25 01:11:38 +00001141 // The range is too big. Emit "if" condition into a new block,
1142 // making sure to save and restore the current insertion point.
1143 llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
Devang Patel2d79d0f2007-10-05 20:54:07 +00001144
Daniel Dunbar16f23572008-07-25 01:11:38 +00001145 // Push this test onto the chain of range checks (which terminates
1146 // in the default basic block). The switch's default will be changed
1147 // to the top of this chain after switch emission is complete.
1148 llvm::BasicBlock *FalseDest = CaseRangeBlock;
Daniel Dunbar55e87422008-11-11 02:29:29 +00001149 CaseRangeBlock = createBasicBlock("sw.caserange");
Devang Patelc049e4f2007-10-08 20:57:48 +00001150
Daniel Dunbar16f23572008-07-25 01:11:38 +00001151 CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1152 Builder.SetInsertPoint(CaseRangeBlock);
Devang Patelc049e4f2007-10-08 20:57:48 +00001153
1154 // Emit range check.
Mike Stump1eb44332009-09-09 15:08:12 +00001155 llvm::Value *Diff =
Benjamin Kramer578faa82011-09-27 21:06:10 +00001156 Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
Mike Stump1eb44332009-09-09 15:08:12 +00001157 llvm::Value *Cond =
Chris Lattner97d54372011-04-19 20:53:45 +00001158 Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
Stephen Hines651f13c2014-04-23 16:59:28 -07001159
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001160 llvm::MDNode *Weights = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001161 if (SwitchWeights) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001162 uint64_t ThisCount = getProfileCount(&S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001163 uint64_t DefaultCount = (*SwitchWeights)[0];
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001164 Weights = createProfileWeights(ThisCount, DefaultCount);
Stephen Hines651f13c2014-04-23 16:59:28 -07001165
1166 // Since we're chaining the switch default through each large case range, we
1167 // need to update the weight for the default, ie, the first case, to include
1168 // this case.
1169 (*SwitchWeights)[0] += ThisCount;
1170 }
1171 Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
Devang Patelc049e4f2007-10-08 20:57:48 +00001172
Daniel Dunbar16f23572008-07-25 01:11:38 +00001173 // Restore the appropriate insertion point.
Daniel Dunbara448fb22008-11-11 23:11:34 +00001174 if (RestoreBB)
1175 Builder.SetInsertPoint(RestoreBB);
1176 else
1177 Builder.ClearInsertionPoint();
Devang Patelc049e4f2007-10-08 20:57:48 +00001178}
1179
1180void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
Fariborz Jahaniand66715d2012-01-16 17:35:57 +00001181 // If there is no enclosing switch instance that we're aware of, then this
1182 // case statement and its block can be elided. This situation only happens
1183 // when we've constant-folded the switch, are emitting the constant case,
Stephen Hines651f13c2014-04-23 16:59:28 -07001184 // and part of the constant case includes another case statement. For
Fariborz Jahaniand66715d2012-01-16 17:35:57 +00001185 // instance: switch (4) { case 4: do { case 5: } while (1); }
Fariborz Jahanian303b4f92012-01-17 23:55:19 +00001186 if (!SwitchInsn) {
1187 EmitStmt(S.getSubStmt());
Fariborz Jahaniand66715d2012-01-16 17:35:57 +00001188 return;
Fariborz Jahanian303b4f92012-01-17 23:55:19 +00001189 }
Fariborz Jahaniand66715d2012-01-16 17:35:57 +00001190
Chris Lattnerb11f9192011-04-17 00:54:30 +00001191 // Handle case ranges.
Devang Patelc049e4f2007-10-08 20:57:48 +00001192 if (S.getRHS()) {
1193 EmitCaseStmtRange(S);
1194 return;
1195 }
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Chris Lattner97d54372011-04-19 20:53:45 +00001197 llvm::ConstantInt *CaseVal =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001198 Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
Chris Lattner97d54372011-04-19 20:53:45 +00001199
Stephen Hines651f13c2014-04-23 16:59:28 -07001200 // If the body of the case is just a 'break', try to not emit an empty block.
1201 // If we're profiling or we're not optimizing, leave the block in for better
1202 // debug and coverage analysis.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001203 if (!CGM.getCodeGenOpts().hasProfileClangInstr() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001204 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
Chad Rosier17083602012-08-24 18:31:16 +00001205 isa<BreakStmt>(S.getSubStmt())) {
Chris Lattnerb11f9192011-04-17 00:54:30 +00001206 JumpDest Block = BreakContinueStack.back().BreakBlock;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001207
Chris Lattnerb11f9192011-04-17 00:54:30 +00001208 // Only do this optimization if there are no cleanups that need emitting.
1209 if (isObviouslyBranchWithoutCleanups(Block)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001210 if (SwitchWeights)
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001211 SwitchWeights->push_back(getProfileCount(&S));
Chris Lattner97d54372011-04-19 20:53:45 +00001212 SwitchInsn->addCase(CaseVal, Block.getBlock());
Chris Lattner42104862011-04-17 23:21:26 +00001213
1214 // If there was a fallthrough into this case, make sure to redirect it to
1215 // the end of the switch as well.
1216 if (Builder.GetInsertBlock()) {
1217 Builder.CreateBr(Block.getBlock());
1218 Builder.ClearInsertionPoint();
1219 }
Chris Lattnerb11f9192011-04-17 00:54:30 +00001220 return;
1221 }
1222 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001223
Stephen Hines651f13c2014-04-23 16:59:28 -07001224 llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001225 EmitBlockWithFallThrough(CaseDest, &S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001226 if (SwitchWeights)
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001227 SwitchWeights->push_back(getProfileCount(&S));
Chris Lattner97d54372011-04-19 20:53:45 +00001228 SwitchInsn->addCase(CaseVal, CaseDest);
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Chris Lattner5512f282009-03-04 04:46:18 +00001230 // Recursively emitting the statement is acceptable, but is not wonderful for
1231 // code where we have many case statements nested together, i.e.:
1232 // case 1:
1233 // case 2:
1234 // case 3: etc.
1235 // Handling this recursively will create a new block for each case statement
1236 // that falls through to the next case which is IR intensive. It also causes
1237 // deep recursion which can run into stack depth limitations. Handle
1238 // sequential non-range case statements specially.
1239 const CaseStmt *CurCase = &S;
1240 const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1241
Chris Lattner97d54372011-04-19 20:53:45 +00001242 // Otherwise, iteratively add consecutive cases to this switch stmt.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001243 while (NextCase && NextCase->getRHS() == nullptr) {
Chris Lattner5512f282009-03-04 04:46:18 +00001244 CurCase = NextCase;
Stephen Hines651f13c2014-04-23 16:59:28 -07001245 llvm::ConstantInt *CaseVal =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001246 Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
Stephen Hines651f13c2014-04-23 16:59:28 -07001247
Stephen Hines651f13c2014-04-23 16:59:28 -07001248 if (SwitchWeights)
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001249 SwitchWeights->push_back(getProfileCount(NextCase));
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001250 if (CGM.getCodeGenOpts().hasProfileClangInstr()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001251 CaseDest = createBasicBlock("sw.bb");
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001252 EmitBlockWithFallThrough(CaseDest, &S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001253 }
1254
Chris Lattner97d54372011-04-19 20:53:45 +00001255 SwitchInsn->addCase(CaseVal, CaseDest);
Chris Lattner5512f282009-03-04 04:46:18 +00001256 NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner5512f282009-03-04 04:46:18 +00001259 // Normal default recursion for non-cases.
1260 EmitStmt(CurCase->getSubStmt());
Devang Patel51b09f22007-10-04 23:45:31 +00001261}
1262
1263void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
Daniel Dunbar16f23572008-07-25 01:11:38 +00001264 llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
Mike Stump1eb44332009-09-09 15:08:12 +00001265 assert(DefaultBlock->empty() &&
Daniel Dunbar55e87422008-11-11 02:29:29 +00001266 "EmitDefaultStmt: Default block already defined?");
Stephen Hines651f13c2014-04-23 16:59:28 -07001267
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001268 EmitBlockWithFallThrough(DefaultBlock, &S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001269
Devang Patel51b09f22007-10-04 23:45:31 +00001270 EmitStmt(S.getSubStmt());
1271}
1272
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001273/// CollectStatementsForCase - Given the body of a 'switch' statement and a
1274/// constant value that is being switched on, see if we can dead code eliminate
1275/// the body of the switch to a simple series of statements to emit. Basically,
1276/// on a switch (5) we want to find these statements:
1277/// case 5:
1278/// printf(...); <--
1279/// ++i; <--
1280/// break;
1281///
1282/// and add them to the ResultStmts vector. If it is unsafe to do this
1283/// transformation (for example, one of the elided statements contains a label
1284/// that might be jumped to), return CSFC_Failure. If we handled it and 'S'
1285/// should include statements after it (e.g. the printf() line is a substmt of
1286/// the case) then return CSFC_FallThrough. If we handled it and found a break
1287/// statement, then return CSFC_Success.
1288///
1289/// If Case is non-null, then we are looking for the specified case, checking
1290/// that nothing we jump over contains labels. If Case is null, then we found
1291/// the case and are looking for the break.
1292///
1293/// If the recursive walk actually finds our Case, then we set FoundCase to
1294/// true.
1295///
1296enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1297static CSFC_Result CollectStatementsForCase(const Stmt *S,
1298 const SwitchCase *Case,
1299 bool &FoundCase,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001300 SmallVectorImpl<const Stmt*> &ResultStmts) {
Chris Lattner38589382011-02-28 01:02:29 +00001301 // If this is a null statement, just succeed.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001302 if (!S)
Chris Lattner38589382011-02-28 01:02:29 +00001303 return Case ? CSFC_Success : CSFC_FallThrough;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001304
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001305 // If this is the switchcase (case 4: or default) that we're looking for, then
1306 // we're in business. Just add the substatement.
1307 if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1308 if (S == Case) {
1309 FoundCase = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001310 return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001311 ResultStmts);
1312 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001313
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001314 // Otherwise, this is some other case or default statement, just ignore it.
1315 return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1316 ResultStmts);
1317 }
Chris Lattner38589382011-02-28 01:02:29 +00001318
1319 // If we are in the live part of the code and we found our break statement,
1320 // return a success!
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001321 if (!Case && isa<BreakStmt>(S))
Chris Lattner38589382011-02-28 01:02:29 +00001322 return CSFC_Success;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001323
Chris Lattner38589382011-02-28 01:02:29 +00001324 // If this is a switch statement, then it might contain the SwitchCase, the
1325 // break, or neither.
1326 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1327 // Handle this as two cases: we might be looking for the SwitchCase (if so
1328 // the skipped statements must be skippable) or we might already have it.
1329 CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1330 if (Case) {
Chris Lattner3f06e272011-02-28 07:22:44 +00001331 // Keep track of whether we see a skipped declaration. The code could be
1332 // using the declaration even if it is skipped, so we can't optimize out
1333 // the decl if the kept statements might refer to it.
1334 bool HadSkippedDecl = false;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001335
Chris Lattner38589382011-02-28 01:02:29 +00001336 // If we're looking for the case, just see if we can skip each of the
1337 // substatements.
1338 for (; Case && I != E; ++I) {
Eli Friedman4d509342011-05-21 19:15:39 +00001339 HadSkippedDecl |= isa<DeclStmt>(*I);
Chad Rosier6f61ba22012-06-20 17:43:05 +00001340
Chris Lattner38589382011-02-28 01:02:29 +00001341 switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1342 case CSFC_Failure: return CSFC_Failure;
1343 case CSFC_Success:
1344 // A successful result means that either 1) that the statement doesn't
1345 // have the case and is skippable, or 2) does contain the case value
Chris Lattner94671102011-02-28 07:16:14 +00001346 // and also contains the break to exit the switch. In the later case,
1347 // we just verify the rest of the statements are elidable.
1348 if (FoundCase) {
Chris Lattner3f06e272011-02-28 07:22:44 +00001349 // If we found the case and skipped declarations, we can't do the
1350 // optimization.
1351 if (HadSkippedDecl)
1352 return CSFC_Failure;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001353
Chris Lattner94671102011-02-28 07:16:14 +00001354 for (++I; I != E; ++I)
1355 if (CodeGenFunction::ContainsLabel(*I, true))
1356 return CSFC_Failure;
1357 return CSFC_Success;
1358 }
Chris Lattner38589382011-02-28 01:02:29 +00001359 break;
1360 case CSFC_FallThrough:
1361 // If we have a fallthrough condition, then we must have found the
1362 // case started to include statements. Consider the rest of the
1363 // statements in the compound statement as candidates for inclusion.
1364 assert(FoundCase && "Didn't find case but returned fallthrough?");
1365 // We recursively found Case, so we're not looking for it anymore.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001366 Case = nullptr;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001367
Chris Lattner3f06e272011-02-28 07:22:44 +00001368 // If we found the case and skipped declarations, we can't do the
1369 // optimization.
1370 if (HadSkippedDecl)
1371 return CSFC_Failure;
Chris Lattner38589382011-02-28 01:02:29 +00001372 break;
1373 }
1374 }
1375 }
1376
1377 // If we have statements in our range, then we know that the statements are
1378 // live and need to be added to the set of statements we're tracking.
1379 for (; I != E; ++I) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001380 switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
Chris Lattner38589382011-02-28 01:02:29 +00001381 case CSFC_Failure: return CSFC_Failure;
1382 case CSFC_FallThrough:
1383 // A fallthrough result means that the statement was simple and just
1384 // included in ResultStmt, keep adding them afterwards.
1385 break;
1386 case CSFC_Success:
1387 // A successful result means that we found the break statement and
1388 // stopped statement inclusion. We just ensure that any leftover stmts
1389 // are skippable and return success ourselves.
1390 for (++I; I != E; ++I)
1391 if (CodeGenFunction::ContainsLabel(*I, true))
1392 return CSFC_Failure;
1393 return CSFC_Success;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001394 }
Chris Lattner38589382011-02-28 01:02:29 +00001395 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001396
Chris Lattner38589382011-02-28 01:02:29 +00001397 return Case ? CSFC_Success : CSFC_FallThrough;
1398 }
1399
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001400 // Okay, this is some other statement that we don't handle explicitly, like a
1401 // for statement or increment etc. If we are skipping over this statement,
1402 // just verify it doesn't have labels, which would make it invalid to elide.
1403 if (Case) {
Chris Lattner3f06e272011-02-28 07:22:44 +00001404 if (CodeGenFunction::ContainsLabel(S, true))
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001405 return CSFC_Failure;
1406 return CSFC_Success;
1407 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001408
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001409 // Otherwise, we want to include this statement. Everything is cool with that
1410 // so long as it doesn't contain a break out of the switch we're in.
1411 if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001412
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001413 // Otherwise, everything is great. Include the statement and tell the caller
1414 // that we fall through and include the next statement as well.
1415 ResultStmts.push_back(S);
1416 return CSFC_FallThrough;
1417}
1418
1419/// FindCaseStatementsForValue - Find the case statement being jumped to and
1420/// then invoke CollectStatementsForCase to find the list of statements to emit
1421/// for a switch on constant. See the comment above CollectStatementsForCase
1422/// for more details.
1423static bool FindCaseStatementsForValue(const SwitchStmt &S,
Richard Trieue1ecdc12012-07-23 20:21:35 +00001424 const llvm::APSInt &ConstantCondValue,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001425 SmallVectorImpl<const Stmt*> &ResultStmts,
Stephen Hines651f13c2014-04-23 16:59:28 -07001426 ASTContext &C,
1427 const SwitchCase *&ResultCase) {
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001428 // First step, find the switch case that is being branched to. We can do this
1429 // efficiently by scanning the SwitchCase list.
1430 const SwitchCase *Case = S.getSwitchCaseList();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001431 const DefaultStmt *DefaultCase = nullptr;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001432
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001433 for (; Case; Case = Case->getNextSwitchCase()) {
1434 // It's either a default or case. Just remember the default statement in
1435 // case we're not jumping to any numbered cases.
1436 if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1437 DefaultCase = DS;
1438 continue;
1439 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001440
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001441 // Check to see if this case is the one we're looking for.
1442 const CaseStmt *CS = cast<CaseStmt>(Case);
1443 // Don't handle case ranges yet.
1444 if (CS->getRHS()) return false;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001445
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001446 // If we found our case, remember it as 'case'.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001447 if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001448 break;
1449 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001450
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001451 // If we didn't find a matching case, we use a default if it exists, or we
1452 // elide the whole switch body!
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001453 if (!Case) {
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001454 // It is safe to elide the body of the switch if it doesn't contain labels
1455 // etc. If it is safe, return successfully with an empty ResultStmts list.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001456 if (!DefaultCase)
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001457 return !CodeGenFunction::ContainsLabel(&S);
1458 Case = DefaultCase;
1459 }
1460
1461 // Ok, we know which case is being jumped to, try to collect all the
1462 // statements that follow it. This can fail for a variety of reasons. Also,
1463 // check to see that the recursive walk actually found our case statement.
1464 // Insane cases like this can fail to find it in the recursive walk since we
1465 // don't handle every stmt kind:
1466 // switch (4) {
1467 // while (1) {
1468 // case 4: ...
1469 bool FoundCase = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001470 ResultCase = Case;
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001471 return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1472 ResultStmts) != CSFC_Failure &&
1473 FoundCase;
1474}
1475
Devang Patel51b09f22007-10-04 23:45:31 +00001476void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
Fariborz Jahanian985df1c2012-01-17 23:39:50 +00001477 // Handle nested switch statements.
1478 llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
Stephen Hines651f13c2014-04-23 16:59:28 -07001479 SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
Fariborz Jahanian985df1c2012-01-17 23:39:50 +00001480 llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1481
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001482 // See if we can constant fold the condition of the switch and therefore only
1483 // emit the live case statement (if any) of the switch.
Richard Trieue1ecdc12012-07-23 20:21:35 +00001484 llvm::APSInt ConstantCondValue;
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001485 if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 SmallVector<const Stmt*, 4> CaseStmts;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001487 const SwitchCase *Case = nullptr;
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001488 if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
Stephen Hines651f13c2014-04-23 16:59:28 -07001489 getContext(), Case)) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001490 if (Case)
1491 incrementProfileCounter(Case);
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001492 RunCleanupsScope ExecutedScope(*this);
1493
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001494 if (S.getInit())
1495 EmitStmt(S.getInit());
1496
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001497 // Emit the condition variable if needed inside the entire cleanup scope
1498 // used by this special case for constant folded switches.
1499 if (S.getConditionVariable())
1500 EmitAutoVarDecl(*S.getConditionVariable());
1501
Fariborz Jahanian985df1c2012-01-17 23:39:50 +00001502 // At this point, we are no longer "within" a switch instance, so
1503 // we can temporarily enforce this to ensure that any embedded case
1504 // statements are not emitted.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001505 SwitchInsn = nullptr;
Fariborz Jahanian985df1c2012-01-17 23:39:50 +00001506
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001507 // Okay, we can dead code eliminate everything except this case. Emit the
1508 // specified series of statements and we're good.
1509 for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1510 EmitStmt(CaseStmts[i]);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001511 incrementProfileCounter(&S);
Fariborz Jahanian985df1c2012-01-17 23:39:50 +00001512
Eric Christopherfc65ec82012-04-10 05:04:04 +00001513 // Now we want to restore the saved switch instance so that nested
1514 // switches continue to function properly
Fariborz Jahanian985df1c2012-01-17 23:39:50 +00001515 SwitchInsn = SavedSwitchInsn;
1516
Chris Lattnerfda0f1f2011-02-28 00:22:07 +00001517 return;
1518 }
1519 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001520
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001521 JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1522
1523 RunCleanupsScope ConditionScope(*this);
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001524
1525 if (S.getInit())
1526 EmitStmt(S.getInit());
1527
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001528 if (S.getConditionVariable())
1529 EmitAutoVarDecl(*S.getConditionVariable());
Devang Patel51b09f22007-10-04 23:45:31 +00001530 llvm::Value *CondV = EmitScalarExpr(S.getCond());
1531
Daniel Dunbar16f23572008-07-25 01:11:38 +00001532 // Create basic block to hold stuff that comes after switch
1533 // statement. We also need to create a default block now so that
1534 // explicit case ranges tests can have a place to jump to on
1535 // failure.
Daniel Dunbar55e87422008-11-11 02:29:29 +00001536 llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
Daniel Dunbar16f23572008-07-25 01:11:38 +00001537 SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07001538 if (PGO.haveRegionCounts()) {
1539 // Walk the SwitchCase list to find how many there are.
1540 uint64_t DefaultCount = 0;
1541 unsigned NumCases = 0;
1542 for (const SwitchCase *Case = S.getSwitchCaseList();
1543 Case;
1544 Case = Case->getNextSwitchCase()) {
1545 if (isa<DefaultStmt>(Case))
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001546 DefaultCount = getProfileCount(Case);
Stephen Hines651f13c2014-04-23 16:59:28 -07001547 NumCases += 1;
1548 }
1549 SwitchWeights = new SmallVector<uint64_t, 16>();
1550 SwitchWeights->reserve(NumCases);
1551 // The default needs to be first. We store the edge count, so we already
1552 // know the right weight.
1553 SwitchWeights->push_back(DefaultCount);
1554 }
Daniel Dunbar16f23572008-07-25 01:11:38 +00001555 CaseRangeBlock = DefaultBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001556
Daniel Dunbar09124252008-11-12 08:21:33 +00001557 // Clear the insertion point to indicate we are in unreachable code.
1558 Builder.ClearInsertionPoint();
Eli Friedmand28a80d2008-05-12 16:08:04 +00001559
Stephen Hines651f13c2014-04-23 16:59:28 -07001560 // All break statements jump to NextBlock. If BreakContinueStack is non-empty
Devang Patele9b8c0a2007-10-30 20:59:40 +00001561 // then reuse last ContinueBlock.
John McCallf1549f62010-07-06 01:34:17 +00001562 JumpDest OuterContinue;
Anders Carlssone4b6d342009-02-10 05:52:02 +00001563 if (!BreakContinueStack.empty())
John McCallf1549f62010-07-06 01:34:17 +00001564 OuterContinue = BreakContinueStack.back().ContinueBlock;
Anders Carlssone4b6d342009-02-10 05:52:02 +00001565
John McCallf1549f62010-07-06 01:34:17 +00001566 BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
Devang Patel51b09f22007-10-04 23:45:31 +00001567
1568 // Emit switch body.
1569 EmitStmt(S.getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Anders Carlssone4b6d342009-02-10 05:52:02 +00001571 BreakContinueStack.pop_back();
Devang Patel51b09f22007-10-04 23:45:31 +00001572
Daniel Dunbar16f23572008-07-25 01:11:38 +00001573 // Update the default block in case explicit case range tests have
1574 // been chained on top.
Stepan Dyatkovskiyab14ae22012-02-01 07:50:21 +00001575 SwitchInsn->setDefaultDest(CaseRangeBlock);
Mike Stump1eb44332009-09-09 15:08:12 +00001576
John McCallf1549f62010-07-06 01:34:17 +00001577 // If a default was never emitted:
Daniel Dunbar16f23572008-07-25 01:11:38 +00001578 if (!DefaultBlock->getParent()) {
John McCallf1549f62010-07-06 01:34:17 +00001579 // If we have cleanups, emit the default block so that there's a
1580 // place to jump through the cleanups from.
1581 if (ConditionScope.requiresCleanups()) {
1582 EmitBlock(DefaultBlock);
1583
1584 // Otherwise, just forward the default block to the switch end.
1585 } else {
John McCallff8e1152010-07-23 21:56:41 +00001586 DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
John McCallf1549f62010-07-06 01:34:17 +00001587 delete DefaultBlock;
1588 }
Daniel Dunbar16f23572008-07-25 01:11:38 +00001589 }
Devang Patel51b09f22007-10-04 23:45:31 +00001590
John McCallff8e1152010-07-23 21:56:41 +00001591 ConditionScope.ForceCleanup();
1592
Daniel Dunbar16f23572008-07-25 01:11:38 +00001593 // Emit continuation.
John McCallff8e1152010-07-23 21:56:41 +00001594 EmitBlock(SwitchExit.getBlock(), true);
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001595 incrementProfileCounter(&S);
Daniel Dunbar16f23572008-07-25 01:11:38 +00001596
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001597 // If the switch has a condition wrapped by __builtin_unpredictable,
1598 // create metadata that specifies that the switch is unpredictable.
1599 // Don't bother if not optimizing because that metadata would not be used.
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07001600 auto *Call = dyn_cast<CallExpr>(S.getCond());
1601 if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) {
1602 auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl());
1603 if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) {
1604 llvm::MDBuilder MDHelper(getLLVMContext());
1605 SwitchInsn->setMetadata(llvm::LLVMContext::MD_unpredictable,
1606 MDHelper.createUnpredictable());
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001607 }
1608 }
1609
Stephen Hines651f13c2014-04-23 16:59:28 -07001610 if (SwitchWeights) {
1611 assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1612 "switch weights do not match switch cases");
1613 // If there's only one jump destination there's no sense weighting it.
1614 if (SwitchWeights->size() > 1)
1615 SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001616 createProfileWeights(*SwitchWeights));
Stephen Hines651f13c2014-04-23 16:59:28 -07001617 delete SwitchWeights;
1618 }
Devang Patel51b09f22007-10-04 23:45:31 +00001619 SwitchInsn = SavedSwitchInsn;
Stephen Hines651f13c2014-04-23 16:59:28 -07001620 SwitchWeights = SavedSwitchWeights;
Devang Patelc049e4f2007-10-08 20:57:48 +00001621 CaseRangeBlock = SavedCRBlock;
Devang Patel51b09f22007-10-04 23:45:31 +00001622}
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001623
Chris Lattner2819fa82009-04-26 17:57:12 +00001624static std::string
Daniel Dunbar444be732009-11-13 05:51:54 +00001625SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001626 SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001627 std::string Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001629 while (*Constraint) {
1630 switch (*Constraint) {
1631 default:
Stuart Hastings002333f2011-06-07 23:45:05 +00001632 Result += Target.convertConstraint(Constraint);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001633 break;
1634 // Ignore these
1635 case '*':
1636 case '?':
1637 case '!':
John Thompsonef44e112010-08-10 19:20:14 +00001638 case '=': // Will see this and the following in mult-alt constraints.
1639 case '+':
1640 break;
Ulrich Weigande6b3dba2012-10-29 12:20:54 +00001641 case '#': // Ignore the rest of the constraint alternative.
1642 while (Constraint[1] && Constraint[1] != ',')
Eric Christopher7b309b02013-07-10 20:14:36 +00001643 Constraint++;
Ulrich Weigande6b3dba2012-10-29 12:20:54 +00001644 break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001645 case '&':
1646 case '%':
1647 Result += *Constraint;
1648 while (Constraint[1] && Constraint[1] == *Constraint)
1649 Constraint++;
1650 break;
John Thompson2f474ea2010-09-18 01:15:13 +00001651 case ',':
1652 Result += "|";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001653 break;
1654 case 'g':
1655 Result += "imr";
1656 break;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001657 case '[': {
Chris Lattner2819fa82009-04-26 17:57:12 +00001658 assert(OutCons &&
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001659 "Must pass output names to constraints with a symbolic name");
1660 unsigned Index;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001661 bool result = Target.resolveSymbolicName(Constraint, *OutCons, Index);
Chris Lattnercbf40f92011-01-05 18:41:53 +00001662 assert(result && "Could not resolve symbolic name"); (void)result;
Anders Carlsson300fb5d2009-01-18 02:06:20 +00001663 Result += llvm::utostr(Index);
1664 break;
1665 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001668 Constraint++;
1669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001671 return Result;
1672}
1673
Rafael Espindola03117d12011-01-01 21:12:33 +00001674/// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1675/// as using a particular register add that as a constraint that will be used
1676/// in this asm stmt.
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001677static std::string
Rafael Espindola03117d12011-01-01 21:12:33 +00001678AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1679 const TargetInfo &Target, CodeGenModule &CGM,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001680 const AsmStmt &Stmt, const bool EarlyClobber) {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001681 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1682 if (!AsmDeclRef)
1683 return Constraint;
1684 const ValueDecl &Value = *AsmDeclRef->getDecl();
1685 const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1686 if (!Variable)
1687 return Constraint;
Eli Friedmana43ef3e2012-03-15 23:12:51 +00001688 if (Variable->getStorageClass() != SC_Register)
1689 return Constraint;
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001690 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1691 if (!Attr)
1692 return Constraint;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001693 StringRef Register = Attr->getLabel();
Rafael Espindolabaf86952011-01-01 21:47:03 +00001694 assert(Target.isValidGCCRegisterName(Register));
Eric Christophere3e07a52011-06-17 01:53:34 +00001695 // We're using validateOutputConstraint here because we only care if
1696 // this is a register constraint.
1697 TargetInfo::ConstraintInfo Info(Constraint, "");
1698 if (Target.validateOutputConstraint(Info) &&
1699 !Info.allowsRegister()) {
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001700 CGM.ErrorUnsupported(&Stmt, "__asm__");
1701 return Constraint;
1702 }
Eric Christopher43fec872011-06-21 00:07:10 +00001703 // Canonicalize the register here before returning it.
1704 Register = Target.getNormalizedGCCRegisterName(Register);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001705 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001706}
1707
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001708llvm::Value*
Chad Rosier42b60552012-08-23 20:00:18 +00001709CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001710 LValue InputValue, QualType InputType,
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001711 std::string &ConstraintStr,
1712 SourceLocation Loc) {
Anders Carlsson63471722009-01-11 19:32:54 +00001713 llvm::Value *Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00001714 if (Info.allowsRegister() || !Info.allowsMemory()) {
John McCall9d232c82013-03-07 21:37:08 +00001715 if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001716 Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
Anders Carlsson63471722009-01-11 19:32:54 +00001717 } else {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001718 llvm::Type *Ty = ConvertType(InputType);
Micah Villmow25a6a842012-10-08 16:25:52 +00001719 uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001720 if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
John McCalld16c2cf2011-02-08 08:22:06 +00001721 Ty = llvm::IntegerType::get(getLLVMContext(), Size);
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001722 Ty = llvm::PointerType::getUnqual(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001724 Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1725 Ty));
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001726 } else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001727 Arg = InputValue.getPointer();
Anders Carlssonebaae2a2009-01-12 02:22:13 +00001728 ConstraintStr += '*';
1729 }
Anders Carlsson63471722009-01-11 19:32:54 +00001730 }
1731 } else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001732 Arg = InputValue.getPointer();
Anders Carlsson63471722009-01-11 19:32:54 +00001733 ConstraintStr += '*';
1734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Anders Carlsson63471722009-01-11 19:32:54 +00001736 return Arg;
1737}
1738
Chad Rosier42b60552012-08-23 20:00:18 +00001739llvm::Value* CodeGenFunction::EmitAsmInput(
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001740 const TargetInfo::ConstraintInfo &Info,
1741 const Expr *InputExpr,
1742 std::string &ConstraintStr) {
Pirama Arumuga Nainarb6d69932015-07-01 12:25:36 -07001743 // If this can't be a register or memory, i.e., has to be a constant
1744 // (immediate or symbolic), try to emit it as such.
1745 if (!Info.allowsRegister() && !Info.allowsMemory()) {
1746 llvm::APSInt Result;
1747 if (InputExpr->EvaluateAsInt(Result, getContext()))
1748 return llvm::ConstantInt::get(getLLVMContext(), Result);
1749 assert(!Info.requiresImmediateConstant() &&
1750 "Required-immediate inlineasm arg isn't constant?");
1751 }
1752
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001753 if (Info.allowsRegister() || !Info.allowsMemory())
John McCall9d232c82013-03-07 21:37:08 +00001754 if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001755 return EmitScalarExpr(InputExpr);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001756 if (InputExpr->getStmtClass() == Expr::CXXThisExprClass)
1757 return EmitScalarExpr(InputExpr);
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001758 InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1759 LValue Dest = EmitLValue(InputExpr);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001760 return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1761 InputExpr->getExprLoc());
Eli Friedman6d7cfd72010-07-16 00:55:21 +00001762}
1763
Chris Lattner47fc7e92010-11-17 05:58:54 +00001764/// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
Chris Lattner5d936532010-11-17 08:25:26 +00001765/// asm call instruction. The !srcloc MDNode contains a list of constant
1766/// integers which are the source locations of the start of each line in the
1767/// asm.
Chris Lattner47fc7e92010-11-17 05:58:54 +00001768static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1769 CodeGenFunction &CGF) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001770 SmallVector<llvm::Metadata *, 8> Locs;
Chris Lattner5d936532010-11-17 08:25:26 +00001771 // Add the location of the first line to the MDNode.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001772 Locs.push_back(llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1773 CGF.Int32Ty, Str->getLocStart().getRawEncoding())));
Chris Lattner5f9e2722011-07-23 10:55:15 +00001774 StringRef StrVal = Str->getString();
Chris Lattner5d936532010-11-17 08:25:26 +00001775 if (!StrVal.empty()) {
1776 const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
David Blaikie4e4d0842012-03-11 07:00:24 +00001777 const LangOptions &LangOpts = CGF.CGM.getLangOpts();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001778 unsigned StartToken = 0;
1779 unsigned ByteOffset = 0;
Chad Rosier6f61ba22012-06-20 17:43:05 +00001780
Chris Lattner5d936532010-11-17 08:25:26 +00001781 // Add the location of the start of each subsequent line of the asm to the
1782 // MDNode.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001783 for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) {
Chris Lattner5d936532010-11-17 08:25:26 +00001784 if (StrVal[i] != '\n') continue;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001785 SourceLocation LineLoc = Str->getLocationOfByte(
1786 i + 1, SM, LangOpts, CGF.getTarget(), &StartToken, &ByteOffset);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001787 Locs.push_back(llvm::ConstantAsMetadata::get(
1788 llvm::ConstantInt::get(CGF.Int32Ty, LineLoc.getRawEncoding())));
Chris Lattner5d936532010-11-17 08:25:26 +00001789 }
Chad Rosier6f61ba22012-06-20 17:43:05 +00001790 }
1791
Jay Foad6f141652011-04-21 19:59:12 +00001792 return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
Chris Lattner47fc7e92010-11-17 05:58:54 +00001793}
1794
Chad Rosiera23b91d2012-08-28 18:54:39 +00001795void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
Chad Rosierbe3ace82012-08-24 17:05:45 +00001796 // Assemble the final asm string.
Chad Rosierda083b22012-08-27 20:23:31 +00001797 std::string AsmString = S.generateAsmString(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Chris Lattner481fef92009-05-03 07:05:00 +00001799 // Get all the output and input constraints together.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001800 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1801 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
Chris Lattner481fef92009-05-03 07:05:00 +00001802
Mike Stump1eb44332009-09-09 15:08:12 +00001803 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
John McCallaeeacf72013-05-03 00:10:13 +00001804 StringRef Name;
1805 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1806 Name = GAS->getOutputName(i);
1807 TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
John McCall64aa4b32013-04-16 22:48:15 +00001808 bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
Stephen Hines651f13c2014-04-23 16:59:28 -07001809 assert(IsValid && "Failed to parse output constraint");
Chris Lattner481fef92009-05-03 07:05:00 +00001810 OutputConstraintInfos.push_back(Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001811 }
1812
Chris Lattner481fef92009-05-03 07:05:00 +00001813 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
John McCallaeeacf72013-05-03 00:10:13 +00001814 StringRef Name;
1815 if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1816 Name = GAS->getInputName(i);
1817 TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
John McCall64aa4b32013-04-16 22:48:15 +00001818 bool IsValid =
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001819 getTarget().validateInputConstraint(OutputConstraintInfos, Info);
Chris Lattnerb9922592010-03-03 21:52:23 +00001820 assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
Chris Lattner481fef92009-05-03 07:05:00 +00001821 InputConstraintInfos.push_back(Info);
1822 }
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001824 std::string Constraints;
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Chris Lattnerede9d902009-05-03 07:53:25 +00001826 std::vector<LValue> ResultRegDests;
1827 std::vector<QualType> ResultRegQualTys;
Jay Foadef6de3d2011-07-11 09:56:20 +00001828 std::vector<llvm::Type *> ResultRegTypes;
1829 std::vector<llvm::Type *> ResultTruncRegTypes;
Chad Rosierd1c0c942012-05-01 19:53:37 +00001830 std::vector<llvm::Type *> ArgTypes;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001831 std::vector<llvm::Value*> Args;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001832
1833 // Keep track of inout constraints.
1834 std::string InOutConstraints;
1835 std::vector<llvm::Value*> InOutArgs;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001836 std::vector<llvm::Type*> InOutArgTypes;
Anders Carlsson03eb5432009-01-27 20:38:24 +00001837
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001838 // An inline asm can be marked readonly if it meets the following conditions:
1839 // - it doesn't have any sideeffects
1840 // - it doesn't clobber memory
1841 // - it doesn't return a value by-reference
1842 // It can be marked readnone if it doesn't have any input memory constraints
1843 // in addition to meeting the conditions listed above.
1844 bool ReadOnly = true, ReadNone = true;
1845
Mike Stump1eb44332009-09-09 15:08:12 +00001846 for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
Chris Lattner481fef92009-05-03 07:05:00 +00001847 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
Anders Carlsson03eb5432009-01-27 20:38:24 +00001848
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001849 // Simplify the output constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001850 std::string OutputConstraint(S.getOutputConstraint(i));
John McCall64aa4b32013-04-16 22:48:15 +00001851 OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1852 getTarget());
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Chris Lattner810f6d52009-03-13 17:38:01 +00001854 const Expr *OutExpr = S.getOutputExpr(i);
1855 OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Eric Christophera18f5392011-06-03 14:52:25 +00001857 OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001858 getTarget(), CGM, S,
1859 Info.earlyClobber());
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001860
Chris Lattner810f6d52009-03-13 17:38:01 +00001861 LValue Dest = EmitLValue(OutExpr);
Chris Lattnerede9d902009-05-03 07:53:25 +00001862 if (!Constraints.empty())
Anders Carlssonbad3a942009-05-01 00:16:04 +00001863 Constraints += ',';
1864
Chris Lattnera077b5c2009-05-03 08:21:20 +00001865 // If this is a register output, then make the inline asm return it
1866 // by-value. If this is a memory result, return the value by-reference.
John McCall9d232c82013-03-07 21:37:08 +00001867 if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
Chris Lattnera077b5c2009-05-03 08:21:20 +00001868 Constraints += "=" + OutputConstraint;
Chris Lattnerede9d902009-05-03 07:53:25 +00001869 ResultRegQualTys.push_back(OutExpr->getType());
1870 ResultRegDests.push_back(Dest);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001871 ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1872 ResultTruncRegTypes.push_back(ResultRegTypes.back());
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Chris Lattnera077b5c2009-05-03 08:21:20 +00001874 // If this output is tied to an input, and if the input is larger, then
1875 // we need to set the actual result type of the inline asm node to be the
1876 // same as the input type.
1877 if (Info.hasMatchingInput()) {
Chris Lattnerebfc9852009-05-03 08:38:58 +00001878 unsigned InputNo;
1879 for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1880 TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
Chris Lattneraab64d02010-04-23 17:27:29 +00001881 if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
Chris Lattnera077b5c2009-05-03 08:21:20 +00001882 break;
Chris Lattnerebfc9852009-05-03 08:38:58 +00001883 }
1884 assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Chris Lattnera077b5c2009-05-03 08:21:20 +00001886 QualType InputTy = S.getInputExpr(InputNo)->getType();
Chris Lattneraab64d02010-04-23 17:27:29 +00001887 QualType OutputType = OutExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Chris Lattnera077b5c2009-05-03 08:21:20 +00001889 uint64_t InputSize = getContext().getTypeSize(InputTy);
Chris Lattneraab64d02010-04-23 17:27:29 +00001890 if (getContext().getTypeSize(OutputType) < InputSize) {
1891 // Form the asm to return the value as a larger integer or fp type.
1892 ResultRegTypes.back() = ConvertType(InputTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00001893 }
1894 }
Tim Northover1bea6532013-06-07 00:04:50 +00001895 if (llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001896 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1897 ResultRegTypes.back()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00001898 ResultRegTypes.back() = AdjTy;
Tim Northover1bea6532013-06-07 00:04:50 +00001899 else {
1900 CGM.getDiags().Report(S.getAsmLoc(),
1901 diag::err_asm_invalid_type_in_input)
1902 << OutExpr->getType() << OutputConstraint;
1903 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001904 } else {
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001905 ArgTypes.push_back(Dest.getAddress().getType());
1906 Args.push_back(Dest.getPointer());
Anders Carlssonf39a4212008-02-05 20:01:53 +00001907 Constraints += "=*";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001908 Constraints += OutputConstraint;
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001909 ReadOnly = ReadNone = false;
Anders Carlssonf39a4212008-02-05 20:01:53 +00001910 }
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Chris Lattner44def072009-04-26 07:16:29 +00001912 if (Info.isReadWrite()) {
Anders Carlssonf39a4212008-02-05 20:01:53 +00001913 InOutConstraints += ',';
Anders Carlsson63471722009-01-11 19:32:54 +00001914
Anders Carlssonfca93612009-08-04 18:18:36 +00001915 const Expr *InputExpr = S.getOutputExpr(i);
Chad Rosier42b60552012-08-23 20:00:18 +00001916 llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001917 InOutConstraints,
1918 InputExpr->getExprLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Bill Wendlingacb53102012-03-22 23:25:07 +00001920 if (llvm::Type* AdjTy =
Tim Northover1bea6532013-06-07 00:04:50 +00001921 getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1922 Arg->getType()))
Bill Wendlingacb53102012-03-22 23:25:07 +00001923 Arg = Builder.CreateBitCast(Arg, AdjTy);
1924
Chris Lattner44def072009-04-26 07:16:29 +00001925 if (Info.allowsRegister())
Anders Carlsson9f2505b2009-01-11 21:23:27 +00001926 InOutConstraints += llvm::utostr(i);
1927 else
1928 InOutConstraints += OutputConstraint;
Anders Carlsson2763b3a2009-01-11 19:46:50 +00001929
Anders Carlssonfca93612009-08-04 18:18:36 +00001930 InOutArgTypes.push_back(Arg->getType());
1931 InOutArgs.push_back(Arg);
Anders Carlssonf39a4212008-02-05 20:01:53 +00001932 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Stephen Hines176edba2014-12-01 14:53:08 -08001935 // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX)
1936 // to the return value slot. Only do this when returning in registers.
1937 if (isa<MSAsmStmt>(&S)) {
1938 const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
1939 if (RetAI.isDirect() || RetAI.isExtend()) {
1940 // Make a fake lvalue for the return value slot.
1941 LValue ReturnSlot = MakeAddrLValue(ReturnValue, FnRetTy);
1942 CGM.getTargetCodeGenInfo().addReturnRegisterOutputs(
1943 *this, ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes,
1944 ResultRegDests, AsmString, S.getNumOutputs());
1945 SawAsmBlock = true;
1946 }
1947 }
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001949 for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1950 const Expr *InputExpr = S.getInputExpr(i);
1951
Chris Lattner481fef92009-05-03 07:05:00 +00001952 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1953
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08001954 if (Info.allowsMemory())
1955 ReadNone = false;
1956
Chris Lattnerede9d902009-05-03 07:53:25 +00001957 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001958 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001960 // Simplify the input constraint.
Chris Lattner481fef92009-05-03 07:05:00 +00001961 std::string InputConstraint(S.getInputConstraint(i));
John McCall64aa4b32013-04-16 22:48:15 +00001962 InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
Chris Lattner2819fa82009-04-26 17:57:12 +00001963 &OutputConstraintInfos);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00001964
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001965 InputConstraint = AddVariableConstraints(
1966 InputConstraint, *InputExpr->IgnoreParenNoopCasts(getContext()),
1967 getTarget(), CGM, S, false /* No EarlyClobber */);
Rafael Espindola0ec89f92010-12-30 22:59:32 +00001968
Chad Rosier42b60552012-08-23 20:00:18 +00001969 llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattner4df4ee02009-05-03 07:27:51 +00001971 // If this input argument is tied to a larger output result, extend the
1972 // input to be the same size as the output. The LLVM backend wants to see
1973 // the input and output of a matching constraint be the same size. Note
1974 // that GCC does not define what the top bits are here. We use zext because
1975 // that is usually cheaper, but LLVM IR should really get an anyext someday.
1976 if (Info.hasTiedOperand()) {
1977 unsigned Output = Info.getTiedOperand();
Chris Lattneraab64d02010-04-23 17:27:29 +00001978 QualType OutputType = S.getOutputExpr(Output)->getType();
Chris Lattner4df4ee02009-05-03 07:27:51 +00001979 QualType InputTy = InputExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Chris Lattneraab64d02010-04-23 17:27:29 +00001981 if (getContext().getTypeSize(OutputType) >
Chris Lattner4df4ee02009-05-03 07:27:51 +00001982 getContext().getTypeSize(InputTy)) {
1983 // Use ptrtoint as appropriate so that we can do our extension.
1984 if (isa<llvm::PointerType>(Arg->getType()))
Chris Lattner77b89b82010-06-27 07:15:29 +00001985 Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001986 llvm::Type *OutputTy = ConvertType(OutputType);
Chris Lattneraab64d02010-04-23 17:27:29 +00001987 if (isa<llvm::IntegerType>(OutputTy))
1988 Arg = Builder.CreateZExt(Arg, OutputTy);
Peter Collingbourne93f13222011-07-29 00:24:50 +00001989 else if (isa<llvm::PointerType>(OutputTy))
1990 Arg = Builder.CreateZExt(Arg, IntPtrTy);
1991 else {
1992 assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
Chris Lattneraab64d02010-04-23 17:27:29 +00001993 Arg = Builder.CreateFPExt(Arg, OutputTy);
Peter Collingbourne93f13222011-07-29 00:24:50 +00001994 }
Chris Lattner4df4ee02009-05-03 07:27:51 +00001995 }
1996 }
Bill Wendlingacb53102012-03-22 23:25:07 +00001997 if (llvm::Type* AdjTy =
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001998 getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1999 Arg->getType()))
Dale Johannesenf6e2c202010-10-29 23:12:32 +00002000 Arg = Builder.CreateBitCast(Arg, AdjTy);
Tim Northover1bea6532013-06-07 00:04:50 +00002001 else
2002 CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
2003 << InputExpr->getType() << InputConstraint;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002005 ArgTypes.push_back(Arg->getType());
2006 Args.push_back(Arg);
2007 Constraints += InputConstraint;
2008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Anders Carlssonf39a4212008-02-05 20:01:53 +00002010 // Append the "input" part of inout constraints last.
2011 for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
2012 ArgTypes.push_back(InOutArgTypes[i]);
2013 Args.push_back(InOutArgs[i]);
2014 }
2015 Constraints += InOutConstraints;
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002017 // Clobbers
2018 for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
Chad Rosier33f05582012-08-27 23:47:56 +00002019 StringRef Clobber = S.getClobber(i);
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002020
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002021 if (Clobber == "memory")
2022 ReadOnly = ReadNone = false;
2023 else if (Clobber != "cc")
Stephen Hines176edba2014-12-01 14:53:08 -08002024 Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Stephen Hines176edba2014-12-01 14:53:08 -08002026 if (!Constraints.empty())
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002027 Constraints += ',';
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Anders Carlssonea041752008-02-06 00:11:32 +00002029 Constraints += "~{";
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002030 Constraints += Clobber;
Anders Carlssonea041752008-02-06 00:11:32 +00002031 Constraints += '}';
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002034 // Add machine specific clobbers
John McCall64aa4b32013-04-16 22:48:15 +00002035 std::string MachineClobbers = getTarget().getClobbers();
Eli Friedmanccf614c2008-12-21 01:15:32 +00002036 if (!MachineClobbers.empty()) {
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002037 if (!Constraints.empty())
2038 Constraints += ',';
Eli Friedmanccf614c2008-12-21 01:15:32 +00002039 Constraints += MachineClobbers;
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002040 }
Anders Carlssonbad3a942009-05-01 00:16:04 +00002041
Chris Lattner2acc6e32011-07-18 04:24:23 +00002042 llvm::Type *ResultType;
Chris Lattnera077b5c2009-05-03 08:21:20 +00002043 if (ResultRegTypes.empty())
Chris Lattner8b418682012-02-07 00:39:47 +00002044 ResultType = VoidTy;
Chris Lattnera077b5c2009-05-03 08:21:20 +00002045 else if (ResultRegTypes.size() == 1)
2046 ResultType = ResultRegTypes[0];
Anders Carlssonbad3a942009-05-01 00:16:04 +00002047 else
John McCalld16c2cf2011-02-08 08:22:06 +00002048 ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Chris Lattner2acc6e32011-07-18 04:24:23 +00002050 llvm::FunctionType *FTy =
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002051 llvm::FunctionType::get(ResultType, ArgTypes, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Chad Rosier2ab7d432012-09-04 19:50:17 +00002053 bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
Chad Rosierfcf75a32012-09-05 19:01:07 +00002054 llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
2055 llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
Mike Stump1eb44332009-09-09 15:08:12 +00002056 llvm::InlineAsm *IA =
Chad Rosier790cbd82012-09-04 23:08:24 +00002057 llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
Chad Rosierfcf75a32012-09-05 19:01:07 +00002058 /* IsAlignStack */ false, AsmDialect);
Jay Foad4c7d9f12011-07-15 08:37:34 +00002059 llvm::CallInst *Result = Builder.CreateCall(IA, Args);
Bill Wendling785b7782012-12-07 23:17:26 +00002060 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
Peter Collingbourne15e05e92013-03-02 01:20:22 +00002061 llvm::Attribute::NoUnwind);
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002063 if (isa<MSAsmStmt>(&S)) {
2064 // If the assembly contains any labels, mark the call noduplicate to prevent
2065 // defining the same ASM label twice (PR23715). This is pretty hacky, but it
2066 // works.
2067 if (AsmString.find("__MSASMLABEL_") != std::string::npos)
2068 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2069 llvm::Attribute::NoDuplicate);
2070 }
2071
2072 // Attach readnone and readonly attributes.
2073 if (!HasSideEffect) {
2074 if (ReadNone)
2075 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2076 llvm::Attribute::ReadNone);
2077 else if (ReadOnly)
2078 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2079 llvm::Attribute::ReadOnly);
2080 }
2081
Chris Lattnerfc1a9c32010-04-07 05:46:54 +00002082 // Slap the source location of the inline asm into a !srcloc metadata on the
Stephen Hines176edba2014-12-01 14:53:08 -08002083 // call.
2084 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S)) {
Chad Rosiera23b91d2012-08-28 18:54:39 +00002085 Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2086 *this));
Stephen Hines176edba2014-12-01 14:53:08 -08002087 } else {
2088 // At least put the line number on MS inline asm blobs.
2089 auto Loc = llvm::ConstantInt::get(Int32Ty, S.getAsmLoc().getRawEncoding());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002090 Result->setMetadata("srcloc",
2091 llvm::MDNode::get(getLLVMContext(),
2092 llvm::ConstantAsMetadata::get(Loc)));
Stephen Hines176edba2014-12-01 14:53:08 -08002093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002095 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
2096 // Conservatively, mark all inline asm blocks in CUDA as convergent
2097 // (meaning, they may call an intrinsically convergent op, such as bar.sync,
2098 // and so can't have certain optimizations applied around them).
2099 Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2100 llvm::Attribute::Convergent);
2101 }
2102
Chris Lattnera077b5c2009-05-03 08:21:20 +00002103 // Extract all of the register value results from the asm.
2104 std::vector<llvm::Value*> RegResults;
2105 if (ResultRegTypes.size() == 1) {
2106 RegResults.push_back(Result);
Anders Carlssonbad3a942009-05-01 00:16:04 +00002107 } else {
Chris Lattnera077b5c2009-05-03 08:21:20 +00002108 for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
Anders Carlssonbad3a942009-05-01 00:16:04 +00002109 llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
Chris Lattnera077b5c2009-05-03 08:21:20 +00002110 RegResults.push_back(Tmp);
Anders Carlssonbad3a942009-05-01 00:16:04 +00002111 }
2112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Stephen Hines176edba2014-12-01 14:53:08 -08002114 assert(RegResults.size() == ResultRegTypes.size());
2115 assert(RegResults.size() == ResultTruncRegTypes.size());
2116 assert(RegResults.size() == ResultRegDests.size());
Chris Lattnera077b5c2009-05-03 08:21:20 +00002117 for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2118 llvm::Value *Tmp = RegResults[i];
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Chris Lattnera077b5c2009-05-03 08:21:20 +00002120 // If the result type of the LLVM IR asm doesn't match the result type of
2121 // the expression, do the conversion.
2122 if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002123 llvm::Type *TruncTy = ResultTruncRegTypes[i];
Chad Rosier6f61ba22012-06-20 17:43:05 +00002124
Chris Lattneraab64d02010-04-23 17:27:29 +00002125 // Truncate the integer result to the right size, note that TruncTy can be
2126 // a pointer.
2127 if (TruncTy->isFloatingPointTy())
2128 Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00002129 else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
Micah Villmow25a6a842012-10-08 16:25:52 +00002130 uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
John McCalld16c2cf2011-02-08 08:22:06 +00002131 Tmp = Builder.CreateTrunc(Tmp,
2132 llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
Chris Lattnera077b5c2009-05-03 08:21:20 +00002133 Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
Dan Gohman2dca88f2010-04-24 04:55:02 +00002134 } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
Micah Villmow25a6a842012-10-08 16:25:52 +00002135 uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
John McCalld16c2cf2011-02-08 08:22:06 +00002136 Tmp = Builder.CreatePtrToInt(Tmp,
2137 llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
Dan Gohman2dca88f2010-04-24 04:55:02 +00002138 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2139 } else if (TruncTy->isIntegerTy()) {
2140 Tmp = Builder.CreateTrunc(Tmp, TruncTy);
Dale Johannesenf6e2c202010-10-29 23:12:32 +00002141 } else if (TruncTy->isVectorTy()) {
2142 Tmp = Builder.CreateBitCast(Tmp, TruncTy);
Chris Lattnera077b5c2009-05-03 08:21:20 +00002143 }
2144 }
Mike Stump1eb44332009-09-09 15:08:12 +00002145
John McCall545d9962011-06-25 02:11:03 +00002146 EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
Chris Lattnera077b5c2009-05-03 08:21:20 +00002147 }
Anders Carlssonfb1aeb82008-02-05 16:35:33 +00002148}
Tareq A. Siraj051303c2013-04-16 18:53:08 +00002149
Stephen Hines176edba2014-12-01 14:53:08 -08002150LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) {
Ben Langmuir524387a2013-05-09 19:17:11 +00002151 const RecordDecl *RD = S.getCapturedRecordDecl();
Stephen Hines176edba2014-12-01 14:53:08 -08002152 QualType RecordTy = getContext().getRecordType(RD);
Ben Langmuir524387a2013-05-09 19:17:11 +00002153
2154 // Initialize the captured struct.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002155 LValue SlotLV =
2156 MakeAddrLValue(CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
Ben Langmuir524387a2013-05-09 19:17:11 +00002157
2158 RecordDecl::field_iterator CurField = RD->field_begin();
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002159 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(),
2160 E = S.capture_init_end();
Ben Langmuir524387a2013-05-09 19:17:11 +00002161 I != E; ++I, ++CurField) {
Stephen Hines176edba2014-12-01 14:53:08 -08002162 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2163 if (CurField->hasCapturedVLAType()) {
2164 auto VAT = CurField->getCapturedVLAType();
2165 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2166 } else {
2167 EmitInitializerForField(*CurField, LV, *I, None);
2168 }
Ben Langmuir524387a2013-05-09 19:17:11 +00002169 }
2170
2171 return SlotLV;
2172}
2173
2174/// Generate an outlined function for the body of a CapturedStmt, store any
2175/// captured variables into the captured struct, and call the outlined function.
2176llvm::Function *
2177CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
Stephen Hines176edba2014-12-01 14:53:08 -08002178 LValue CapStruct = InitCapturedStruct(S);
Ben Langmuir524387a2013-05-09 19:17:11 +00002179
2180 // Emit the CapturedDecl
2181 CodeGenFunction CGF(CGM, true);
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002182 CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K));
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002183 llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
Ben Langmuir524387a2013-05-09 19:17:11 +00002184 delete CGF.CapturedStmtInfo;
2185
2186 // Emit call to the helper function.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002187 EmitCallOrInvoke(F, CapStruct.getPointer());
Ben Langmuir524387a2013-05-09 19:17:11 +00002188
2189 return F;
2190}
2191
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002192Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
Stephen Hines176edba2014-12-01 14:53:08 -08002193 LValue CapStruct = InitCapturedStruct(S);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002194 return CapStruct.getAddress();
2195}
2196
Ben Langmuir524387a2013-05-09 19:17:11 +00002197/// Creates the outlined function for a CapturedStmt.
2198llvm::Function *
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002199CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
Ben Langmuir524387a2013-05-09 19:17:11 +00002200 assert(CapturedStmtInfo &&
2201 "CapturedStmtInfo should be set when generating the captured function");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002202 const CapturedDecl *CD = S.getCapturedDecl();
2203 const RecordDecl *RD = S.getCapturedRecordDecl();
2204 SourceLocation Loc = S.getLocStart();
2205 assert(CD->hasBody() && "missing CapturedDecl body");
Ben Langmuir524387a2013-05-09 19:17:11 +00002206
Ben Langmuir524387a2013-05-09 19:17:11 +00002207 // Build the argument list.
2208 ASTContext &Ctx = CGM.getContext();
2209 FunctionArgList Args;
2210 Args.append(CD->param_begin(), CD->param_end());
2211
2212 // Create the function declaration.
2213 FunctionType::ExtInfo ExtInfo;
2214 const CGFunctionInfo &FuncInfo =
Pirama Arumuga Nainar4967a712016-09-19 22:19:55 -07002215 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, Args);
Ben Langmuir524387a2013-05-09 19:17:11 +00002216 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2217
2218 llvm::Function *F =
2219 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2220 CapturedStmtInfo->getHelperName(), &CGM.getModule());
2221 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002222 if (CD->isNothrow())
2223 F->addFnAttr(llvm::Attribute::NoUnwind);
Ben Langmuir524387a2013-05-09 19:17:11 +00002224
2225 // Generate the function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002226 StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2227 CD->getLocation(),
2228 CD->getBody()->getLocStart());
Ben Langmuir524387a2013-05-09 19:17:11 +00002229 // Set the context parameter in CapturedStmtInfo.
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002230 Address DeclPtr = GetAddrOfLocalVar(CD->getContextParam());
Ben Langmuir524387a2013-05-09 19:17:11 +00002231 CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2232
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002233 // Initialize variable-length arrays.
Stephen Hines176edba2014-12-01 14:53:08 -08002234 LValue Base = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2235 Ctx.getTagDeclType(RD));
2236 for (auto *FD : RD->fields()) {
2237 if (FD->hasCapturedVLAType()) {
2238 auto *ExprArg = EmitLoadOfLValue(EmitLValueForField(Base, FD),
2239 S.getLocStart()).getScalarVal();
2240 auto VAT = FD->getCapturedVLAType();
2241 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
2242 }
2243 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002244
Ben Langmuir524387a2013-05-09 19:17:11 +00002245 // If 'this' is captured, load it into CXXThisValue.
2246 if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2247 FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
Stephen Hines176edba2014-12-01 14:53:08 -08002248 LValue ThisLValue = EmitLValueForField(Base, FD);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002249 CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
Ben Langmuir524387a2013-05-09 19:17:11 +00002250 }
2251
Pirama Arumuga Nainar87d948e2016-03-03 15:49:35 -08002252 PGO.assignRegionCounters(GlobalDecl(CD), F);
Ben Langmuir524387a2013-05-09 19:17:11 +00002253 CapturedStmtInfo->EmitBody(*this, CD->getBody());
2254 FinishFunction(CD->getBodyRBrace());
2255
2256 return F;
Tareq A. Siraj051303c2013-04-16 18:53:08 +00002257}