1//===---- CGLoopInfo.cpp - LLVM CodeGen for loop metadata -*- C++ -*-------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "CGLoopInfo.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/Expr.h"
13#include "clang/Basic/CodeGenOptions.h"
14#include "llvm/IR/BasicBlock.h"
15#include "llvm/IR/CFG.h"
16#include "llvm/IR/Constants.h"
17#include "llvm/IR/InstrTypes.h"
18#include "llvm/IR/Instructions.h"
19#include "llvm/IR/Metadata.h"
20#include <optional>
21using namespace clang::CodeGen;
22using namespace llvm;
23
24MDNode *clang::CodeGen::LoopInfo::createFollowupMetadata(
25 const char *FollowupName, ArrayRef<llvm::Metadata *> LoopProperties) {
26 LLVMContext &Ctx = Header->getContext();
27
28 SmallVector<Metadata *, 4> Args;
29 Args.push_back(Elt: MDString::get(Context&: Ctx, Str: FollowupName));
30 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
31 return MDNode::get(Context&: Ctx, MDs: Args);
32}
33
34SmallVector<Metadata *, 4> clang::CodeGen::LoopInfo::createPipeliningMetadata(
35 const LoopAttributes &Attrs, ArrayRef<Metadata *> LoopProperties,
36 bool &HasUserTransforms) {
37 LLVMContext &Ctx = Header->getContext();
38
39 std::optional<bool> Enabled;
40 if (Attrs.PipelineDisabled)
41 Enabled = false;
42 else if (Attrs.PipelineInitiationInterval != 0)
43 Enabled = true;
44
45 SmallVector<Metadata *, 4> Args;
46 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
47
48 if (Enabled != true) {
49 if (Enabled == false) {
50 Args.push_back(
51 Elt: MDNode::get(Context&: Ctx, MDs: {MDString::get(Context&: Ctx, Str: "llvm.loop.pipeline.disable"),
52 ConstantAsMetadata::get(C: ConstantInt::get(
53 Ty: llvm::Type::getInt1Ty(C&: Ctx), V: 1))}));
54 }
55 return Args;
56 }
57
58 if (Attrs.PipelineInitiationInterval > 0) {
59 Metadata *Vals[] = {
60 MDString::get(Context&: Ctx, Str: "llvm.loop.pipeline.initiationinterval"),
61 ConstantAsMetadata::get(C: ConstantInt::get(
62 Ty: llvm::Type::getInt32Ty(C&: Ctx), V: Attrs.PipelineInitiationInterval))};
63 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
64 }
65
66 // No follow-up: This is the last transformation.
67
68 HasUserTransforms = true;
69 return Args;
70}
71
72SmallVector<Metadata *, 4>
73clang::CodeGen::LoopInfo::createPartialUnrollMetadata(
74 const LoopAttributes &Attrs, ArrayRef<Metadata *> LoopProperties,
75 bool &HasUserTransforms) {
76 LLVMContext &Ctx = Header->getContext();
77
78 std::optional<bool> Enabled;
79 if (Attrs.UnrollEnable == LoopAttributes::Disable)
80 Enabled = false;
81 else if (Attrs.UnrollEnable == LoopAttributes::Full)
82 Enabled = std::nullopt;
83 else if (Attrs.UnrollEnable != LoopAttributes::Unspecified ||
84 Attrs.UnrollCount != 0)
85 Enabled = true;
86
87 if (Enabled != true) {
88 // createFullUnrollMetadata will already have added llvm.loop.unroll.disable
89 // if unrolling is disabled.
90 return createPipeliningMetadata(Attrs, LoopProperties, HasUserTransforms);
91 }
92
93 SmallVector<Metadata *, 4> FollowupLoopProperties;
94
95 // Apply all loop properties to the unrolled loop.
96 FollowupLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
97
98 // Don't unroll an already unrolled loop.
99 FollowupLoopProperties.push_back(
100 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.unroll.disable")));
101
102 bool FollowupHasTransforms = false;
103 SmallVector<Metadata *, 4> Followup = createPipeliningMetadata(
104 Attrs, LoopProperties: FollowupLoopProperties, HasUserTransforms&: FollowupHasTransforms);
105
106 SmallVector<Metadata *, 4> Args;
107 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
108
109 // Setting unroll.count
110 if (Attrs.UnrollCount > 0) {
111 Metadata *Vals[] = {MDString::get(Context&: Ctx, Str: "llvm.loop.unroll.count"),
112 ConstantAsMetadata::get(C: ConstantInt::get(
113 Ty: llvm::Type::getInt32Ty(C&: Ctx), V: Attrs.UnrollCount))};
114 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
115 }
116
117 // Setting unroll.full or unroll.disable
118 if (Attrs.UnrollEnable == LoopAttributes::Enable) {
119 Metadata *Vals[] = {MDString::get(Context&: Ctx, Str: "llvm.loop.unroll.enable")};
120 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
121 }
122
123 if (FollowupHasTransforms)
124 Args.push_back(
125 Elt: createFollowupMetadata(FollowupName: "llvm.loop.unroll.followup_all", LoopProperties: Followup));
126
127 HasUserTransforms = true;
128 return Args;
129}
130
131SmallVector<Metadata *, 4> clang::CodeGen::LoopInfo::createUnrollAndJamMetadata(
132 const LoopAttributes &Attrs, ArrayRef<Metadata *> LoopProperties,
133 bool &HasUserTransforms) {
134 LLVMContext &Ctx = Header->getContext();
135
136 std::optional<bool> Enabled;
137 if (Attrs.UnrollAndJamEnable == LoopAttributes::Disable)
138 Enabled = false;
139 else if (Attrs.UnrollAndJamEnable == LoopAttributes::Enable ||
140 Attrs.UnrollAndJamCount != 0)
141 Enabled = true;
142
143 if (Enabled != true) {
144 SmallVector<Metadata *, 4> NewLoopProperties;
145 if (Enabled == false) {
146 NewLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
147 NewLoopProperties.push_back(Elt: MDNode::get(
148 Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.unroll_and_jam.disable")));
149 LoopProperties = NewLoopProperties;
150 }
151 return createPartialUnrollMetadata(Attrs, LoopProperties,
152 HasUserTransforms);
153 }
154
155 SmallVector<Metadata *, 4> FollowupLoopProperties;
156 FollowupLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
157 FollowupLoopProperties.push_back(
158 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.unroll_and_jam.disable")));
159
160 bool FollowupHasTransforms = false;
161 SmallVector<Metadata *, 4> Followup = createPartialUnrollMetadata(
162 Attrs, LoopProperties: FollowupLoopProperties, HasUserTransforms&: FollowupHasTransforms);
163
164 SmallVector<Metadata *, 4> Args;
165 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
166
167 // Setting unroll_and_jam.count
168 if (Attrs.UnrollAndJamCount > 0) {
169 Metadata *Vals[] = {
170 MDString::get(Context&: Ctx, Str: "llvm.loop.unroll_and_jam.count"),
171 ConstantAsMetadata::get(C: ConstantInt::get(Ty: llvm::Type::getInt32Ty(C&: Ctx),
172 V: Attrs.UnrollAndJamCount))};
173 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
174 }
175
176 if (Attrs.UnrollAndJamEnable == LoopAttributes::Enable) {
177 Metadata *Vals[] = {MDString::get(Context&: Ctx, Str: "llvm.loop.unroll_and_jam.enable")};
178 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
179 }
180
181 if (FollowupHasTransforms)
182 Args.push_back(Elt: createFollowupMetadata(
183 FollowupName: "llvm.loop.unroll_and_jam.followup_outer", LoopProperties: Followup));
184
185 if (UnrollAndJamInnerFollowup.has_value())
186 Args.push_back(Elt: createFollowupMetadata(
187 FollowupName: "llvm.loop.unroll_and_jam.followup_inner", LoopProperties: *UnrollAndJamInnerFollowup));
188
189 HasUserTransforms = true;
190 return Args;
191}
192
193SmallVector<Metadata *, 4>
194clang::CodeGen::LoopInfo::createLoopVectorizeMetadata(
195 const LoopAttributes &Attrs, ArrayRef<Metadata *> LoopProperties,
196 bool &HasUserTransforms) {
197 LLVMContext &Ctx = Header->getContext();
198
199 std::optional<bool> Enabled;
200 if (Attrs.VectorizeEnable == LoopAttributes::Disable)
201 Enabled = false;
202 else if (Attrs.VectorizeEnable != LoopAttributes::Unspecified ||
203 Attrs.VectorizePredicateEnable != LoopAttributes::Unspecified ||
204 Attrs.InterleaveCount != 0 || Attrs.VectorizeWidth != 0 ||
205 Attrs.VectorizeScalable != LoopAttributes::Unspecified)
206 Enabled = true;
207
208 if (Enabled != true) {
209 SmallVector<Metadata *, 4> NewLoopProperties;
210 if (Enabled == false) {
211 NewLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
212 NewLoopProperties.push_back(
213 Elt: MDNode::get(Context&: Ctx, MDs: {MDString::get(Context&: Ctx, Str: "llvm.loop.vectorize.enable"),
214 ConstantAsMetadata::get(C: ConstantInt::get(
215 Ty: llvm::Type::getInt1Ty(C&: Ctx), V: 0))}));
216 LoopProperties = NewLoopProperties;
217 }
218 return createUnrollAndJamMetadata(Attrs, LoopProperties, HasUserTransforms);
219 }
220
221 SmallVector<Metadata *, 4> Args;
222 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
223
224 // Setting vectorize.predicate when it has been specified and vectorization
225 // has not been disabled.
226 bool IsVectorPredicateEnabled = false;
227 if (Attrs.VectorizePredicateEnable != LoopAttributes::Unspecified) {
228 IsVectorPredicateEnabled =
229 (Attrs.VectorizePredicateEnable == LoopAttributes::Enable);
230
231 Metadata *Vals[] = {
232 MDString::get(Context&: Ctx, Str: "llvm.loop.vectorize.predicate.enable"),
233 ConstantAsMetadata::get(C: ConstantInt::get(Ty: llvm::Type::getInt1Ty(C&: Ctx),
234 V: IsVectorPredicateEnabled))};
235 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
236 }
237
238 // Setting vectorize.width
239 if (Attrs.VectorizeWidth > 0) {
240 Metadata *Vals[] = {
241 MDString::get(Context&: Ctx, Str: "llvm.loop.vectorize.width"),
242 ConstantAsMetadata::get(C: ConstantInt::get(Ty: llvm::Type::getInt32Ty(C&: Ctx),
243 V: Attrs.VectorizeWidth))};
244
245 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
246 }
247
248 if (Attrs.VectorizeScalable != LoopAttributes::Unspecified) {
249 bool IsScalable = Attrs.VectorizeScalable == LoopAttributes::Enable;
250 Metadata *Vals[] = {
251 MDString::get(Context&: Ctx, Str: "llvm.loop.vectorize.scalable.enable"),
252 ConstantAsMetadata::get(
253 C: ConstantInt::get(Ty: llvm::Type::getInt1Ty(C&: Ctx), V: IsScalable))};
254 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
255 }
256
257 // Setting interleave.count
258 if (Attrs.InterleaveCount > 0) {
259 Metadata *Vals[] = {
260 MDString::get(Context&: Ctx, Str: "llvm.loop.interleave.count"),
261 ConstantAsMetadata::get(C: ConstantInt::get(Ty: llvm::Type::getInt32Ty(C&: Ctx),
262 V: Attrs.InterleaveCount))};
263 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
264 }
265
266 // vectorize.enable is set if:
267 // 1) loop hint vectorize.enable is set, or
268 // 2) it is implied when vectorize.predicate is set, or
269 // 3) it is implied when vectorize.width is set to a value > 1
270 // 4) it is implied when vectorize.scalable.enable is true
271 // 5) it is implied when vectorize.width is unset (0) and the user
272 // explicitly requested fixed-width vectorization, i.e.
273 // vectorize.scalable.enable is false.
274 bool VectorizeEnabled = false;
275 if (Attrs.VectorizeEnable != LoopAttributes::Unspecified ||
276 (IsVectorPredicateEnabled && Attrs.VectorizeWidth != 1) ||
277 Attrs.VectorizeWidth > 1 ||
278 Attrs.VectorizeScalable == LoopAttributes::Enable ||
279 (Attrs.VectorizeScalable == LoopAttributes::Disable &&
280 Attrs.VectorizeWidth != 1)) {
281 VectorizeEnabled = Attrs.VectorizeEnable != LoopAttributes::Disable;
282 Args.push_back(
283 Elt: MDNode::get(Context&: Ctx, MDs: {MDString::get(Context&: Ctx, Str: "llvm.loop.vectorize.enable"),
284 ConstantAsMetadata::get(C: ConstantInt::get(
285 Ty: llvm::Type::getInt1Ty(C&: Ctx), V: VectorizeEnabled))}));
286 }
287
288 // Apply all loop properties to the vectorized loop.
289 SmallVector<Metadata *, 4> FollowupLoopProperties;
290
291 // If vectorization is not explicitly enabled, the follow-up metadata will be
292 // directly appended to the list currently being created. In that case, adding
293 // LoopProperties to FollowupLoopProperties would result in duplication.
294 if (VectorizeEnabled)
295 FollowupLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
296
297 // Don't vectorize an already vectorized loop.
298 FollowupLoopProperties.push_back(
299 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.isvectorized")));
300
301 bool FollowupHasTransforms = false;
302 SmallVector<Metadata *, 4> Followup = createUnrollAndJamMetadata(
303 Attrs, LoopProperties: FollowupLoopProperties, HasUserTransforms&: FollowupHasTransforms);
304
305 if (FollowupHasTransforms) {
306 // If vectorization is explicitly enabled, we create a follow-up metadata,
307 // otherwise directly add the contents of it to Args.
308 if (VectorizeEnabled)
309 Args.push_back(
310 Elt: createFollowupMetadata(FollowupName: "llvm.loop.vectorize.followup_all", LoopProperties: Followup));
311 else
312 Args.append(in_start: Followup.begin(), in_end: Followup.end());
313 }
314
315 HasUserTransforms = true;
316 return Args;
317}
318
319SmallVector<Metadata *, 4>
320clang::CodeGen::LoopInfo::createLoopDistributeMetadata(
321 const LoopAttributes &Attrs, ArrayRef<Metadata *> LoopProperties,
322 bool &HasUserTransforms) {
323 LLVMContext &Ctx = Header->getContext();
324
325 std::optional<bool> Enabled;
326 if (Attrs.DistributeEnable == LoopAttributes::Disable)
327 Enabled = false;
328 if (Attrs.DistributeEnable == LoopAttributes::Enable)
329 Enabled = true;
330
331 if (Enabled != true) {
332 SmallVector<Metadata *, 4> NewLoopProperties;
333 if (Enabled == false) {
334 NewLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
335 NewLoopProperties.push_back(Elt: MDNode::get(
336 Context&: Ctx, MDs: {MDString::get(Context&: Ctx, Str: "llvm.loop.distribute.disable")}));
337 LoopProperties = NewLoopProperties;
338 }
339 return createLoopVectorizeMetadata(Attrs, LoopProperties,
340 HasUserTransforms);
341 }
342
343 bool FollowupHasTransforms = false;
344 SmallVector<Metadata *, 4> Followup =
345 createLoopVectorizeMetadata(Attrs, LoopProperties, HasUserTransforms&: FollowupHasTransforms);
346
347 SmallVector<Metadata *, 4> Args;
348 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
349
350 Args.push_back(
351 Elt: MDNode::get(Context&: Ctx, MDs: {MDString::get(Context&: Ctx, Str: "llvm.loop.distribute.enable")}));
352
353 if (FollowupHasTransforms)
354 Args.push_back(
355 Elt: createFollowupMetadata(FollowupName: "llvm.loop.distribute.followup_all", LoopProperties: Followup));
356
357 HasUserTransforms = true;
358 return Args;
359}
360
361SmallVector<Metadata *, 4> clang::CodeGen::LoopInfo::createFullUnrollMetadata(
362 const LoopAttributes &Attrs, ArrayRef<Metadata *> LoopProperties,
363 bool &HasUserTransforms) {
364 LLVMContext &Ctx = Header->getContext();
365
366 std::optional<bool> Enabled;
367 if (Attrs.UnrollEnable == LoopAttributes::Disable)
368 Enabled = false;
369 else if (Attrs.UnrollEnable == LoopAttributes::Full)
370 Enabled = true;
371
372 if (Enabled != true) {
373 SmallVector<Metadata *, 4> NewLoopProperties;
374 if (Enabled == false) {
375 NewLoopProperties.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
376 NewLoopProperties.push_back(
377 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.unroll.disable")));
378 LoopProperties = NewLoopProperties;
379 }
380 return createLoopDistributeMetadata(Attrs, LoopProperties,
381 HasUserTransforms);
382 }
383
384 SmallVector<Metadata *, 4> Args;
385 Args.append(in_start: LoopProperties.begin(), in_end: LoopProperties.end());
386 Args.push_back(Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.unroll.full")));
387
388 // No follow-up: there is no loop after full unrolling.
389 // TODO: Warn if there are transformations after full unrolling.
390
391 HasUserTransforms = true;
392 return Args;
393}
394
395SmallVector<Metadata *, 4> clang::CodeGen::LoopInfo::createMetadata(
396 const LoopAttributes &Attrs,
397 llvm::ArrayRef<llvm::Metadata *> AdditionalLoopProperties,
398 bool &HasUserTransforms) {
399 SmallVector<Metadata *, 3> LoopProperties;
400
401 // If we have a valid start debug location for the loop, add it.
402 if (StartLoc) {
403 LoopProperties.push_back(Elt: StartLoc.getAsMDNode());
404
405 // If we also have a valid end debug location for the loop, add it.
406 if (EndLoc)
407 LoopProperties.push_back(Elt: EndLoc.getAsMDNode());
408 }
409
410 LLVMContext &Ctx = Header->getContext();
411 if (Attrs.MustProgress)
412 LoopProperties.push_back(
413 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.mustprogress")));
414
415 if (Attrs.LICMDisabled)
416 LoopProperties.push_back(
417 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.licm.disable")));
418
419 assert(!!AccGroup == Attrs.IsParallel &&
420 "There must be an access group iff the loop is parallel");
421 if (Attrs.IsParallel) {
422 LoopProperties.push_back(Elt: MDNode::get(
423 Context&: Ctx, MDs: {MDString::get(Context&: Ctx, Str: "llvm.loop.parallel_accesses"), AccGroup}));
424 }
425
426 // Setting clang::code_align attribute.
427 if (Attrs.CodeAlign > 0) {
428 Metadata *Vals[] = {MDString::get(Context&: Ctx, Str: "llvm.loop.align"),
429 ConstantAsMetadata::get(C: ConstantInt::get(
430 Ty: llvm::Type::getInt32Ty(C&: Ctx), V: Attrs.CodeAlign))};
431 LoopProperties.push_back(Elt: MDNode::get(Context&: Ctx, MDs: Vals));
432 }
433
434 llvm::append_range(C&: LoopProperties, R&: AdditionalLoopProperties);
435 return createFullUnrollMetadata(Attrs, LoopProperties, HasUserTransforms);
436}
437
438LoopAttributes::LoopAttributes(bool IsParallel)
439 : IsParallel(IsParallel), VectorizeEnable(LoopAttributes::Unspecified),
440 UnrollEnable(LoopAttributes::Unspecified),
441 UnrollAndJamEnable(LoopAttributes::Unspecified),
442 VectorizePredicateEnable(LoopAttributes::Unspecified), VectorizeWidth(0),
443 VectorizeScalable(LoopAttributes::Unspecified), InterleaveCount(0),
444 UnrollCount(0), UnrollAndJamCount(0),
445 DistributeEnable(LoopAttributes::Unspecified), PipelineDisabled(false),
446 LICMDisabled(false), PipelineInitiationInterval(0), CodeAlign(0),
447 MustProgress(false) {}
448
449void LoopAttributes::clear() {
450 IsParallel = false;
451 VectorizeWidth = 0;
452 VectorizeScalable = LoopAttributes::Unspecified;
453 InterleaveCount = 0;
454 UnrollCount = 0;
455 UnrollAndJamCount = 0;
456 VectorizeEnable = LoopAttributes::Unspecified;
457 UnrollEnable = LoopAttributes::Unspecified;
458 UnrollAndJamEnable = LoopAttributes::Unspecified;
459 VectorizePredicateEnable = LoopAttributes::Unspecified;
460 DistributeEnable = LoopAttributes::Unspecified;
461 PipelineDisabled = false;
462 LICMDisabled = false;
463 PipelineInitiationInterval = 0;
464 CodeAlign = 0;
465 MustProgress = false;
466}
467
468clang::CodeGen::LoopInfo::LoopInfo(BasicBlock *Header,
469 const LoopAttributes &Attrs,
470 const llvm::DebugLoc &StartLoc,
471 const llvm::DebugLoc &EndLoc,
472 LoopInfo *Parent)
473 : Header(Header), Attrs(Attrs), StartLoc(StartLoc), EndLoc(EndLoc),
474 Parent(Parent) {
475
476 if (Attrs.IsParallel) {
477 // Create an access group for this loop.
478 LLVMContext &Ctx = Header->getContext();
479 AccGroup = MDNode::getDistinct(Context&: Ctx, MDs: {});
480 }
481
482 if (!Attrs.IsParallel && Attrs.VectorizeWidth == 0 &&
483 Attrs.VectorizeScalable == LoopAttributes::Unspecified &&
484 Attrs.InterleaveCount == 0 && Attrs.UnrollCount == 0 &&
485 Attrs.UnrollAndJamCount == 0 && !Attrs.PipelineDisabled &&
486 !Attrs.LICMDisabled && Attrs.PipelineInitiationInterval == 0 &&
487 Attrs.VectorizePredicateEnable == LoopAttributes::Unspecified &&
488 Attrs.VectorizeEnable == LoopAttributes::Unspecified &&
489 Attrs.UnrollEnable == LoopAttributes::Unspecified &&
490 Attrs.UnrollAndJamEnable == LoopAttributes::Unspecified &&
491 Attrs.DistributeEnable == LoopAttributes::Unspecified &&
492 Attrs.CodeAlign == 0 && !StartLoc && !EndLoc && !Attrs.MustProgress)
493 return;
494
495 TempLoopID = MDNode::getTemporary(Context&: Header->getContext(), MDs: {});
496}
497
498void clang::CodeGen::LoopInfo::finish() {
499 // We did not annotate the loop body instructions because there are no
500 // attributes for this loop.
501 if (!TempLoopID)
502 return;
503
504 MDNode *LoopID;
505 LoopAttributes CurLoopAttr = Attrs;
506 LLVMContext &Ctx = Header->getContext();
507
508 if (Parent && (Parent->Attrs.UnrollAndJamEnable ||
509 Parent->Attrs.UnrollAndJamCount != 0)) {
510 // Parent unroll-and-jams this loop.
511 // Split the transformations in those that happens before the unroll-and-jam
512 // and those after.
513
514 LoopAttributes BeforeJam, AfterJam;
515
516 BeforeJam.IsParallel = AfterJam.IsParallel = Attrs.IsParallel;
517
518 BeforeJam.VectorizeWidth = Attrs.VectorizeWidth;
519 BeforeJam.VectorizeScalable = Attrs.VectorizeScalable;
520 BeforeJam.InterleaveCount = Attrs.InterleaveCount;
521 BeforeJam.VectorizeEnable = Attrs.VectorizeEnable;
522 BeforeJam.DistributeEnable = Attrs.DistributeEnable;
523 BeforeJam.VectorizePredicateEnable = Attrs.VectorizePredicateEnable;
524 BeforeJam.LICMDisabled = Attrs.LICMDisabled;
525
526 switch (Attrs.UnrollEnable) {
527 case LoopAttributes::Unspecified:
528 case LoopAttributes::Disable:
529 BeforeJam.UnrollEnable = Attrs.UnrollEnable;
530 AfterJam.UnrollEnable = Attrs.UnrollEnable;
531 break;
532 case LoopAttributes::Full:
533 BeforeJam.UnrollEnable = LoopAttributes::Full;
534 break;
535 case LoopAttributes::Enable:
536 AfterJam.UnrollEnable = LoopAttributes::Enable;
537 break;
538 }
539
540 AfterJam.VectorizePredicateEnable = Attrs.VectorizePredicateEnable;
541 AfterJam.UnrollCount = Attrs.UnrollCount;
542 AfterJam.PipelineDisabled = Attrs.PipelineDisabled;
543 AfterJam.PipelineInitiationInterval = Attrs.PipelineInitiationInterval;
544
545 // If this loop is subject of an unroll-and-jam by the parent loop, and has
546 // an unroll-and-jam annotation itself, we have to decide whether to first
547 // apply the parent's unroll-and-jam or this loop's unroll-and-jam. The
548 // UnrollAndJam pass processes loops from inner to outer, so we apply the
549 // inner first.
550 BeforeJam.UnrollAndJamCount = Attrs.UnrollAndJamCount;
551 BeforeJam.UnrollAndJamEnable = Attrs.UnrollAndJamEnable;
552
553 // Set the inner followup metadata to process by the outer loop. Only
554 // consider the first inner loop.
555 if (!Parent->UnrollAndJamInnerFollowup) {
556 // Splitting the attributes into a BeforeJam and an AfterJam part will
557 // stop 'llvm.loop.isvectorized' (generated by vectorization in BeforeJam)
558 // to be forwarded to the AfterJam part. We detect the situation here and
559 // add it manually.
560 SmallVector<Metadata *, 1> BeforeLoopProperties;
561 if (BeforeJam.VectorizeEnable != LoopAttributes::Unspecified ||
562 BeforeJam.VectorizePredicateEnable != LoopAttributes::Unspecified ||
563 BeforeJam.InterleaveCount != 0 || BeforeJam.VectorizeWidth != 0 ||
564 BeforeJam.VectorizeScalable == LoopAttributes::Enable)
565 BeforeLoopProperties.push_back(
566 Elt: MDNode::get(Context&: Ctx, MDs: MDString::get(Context&: Ctx, Str: "llvm.loop.isvectorized")));
567
568 bool InnerFollowupHasTransform = false;
569 SmallVector<Metadata *, 4> InnerFollowup = createMetadata(
570 Attrs: AfterJam, AdditionalLoopProperties: BeforeLoopProperties, HasUserTransforms&: InnerFollowupHasTransform);
571 if (InnerFollowupHasTransform)
572 Parent->UnrollAndJamInnerFollowup = InnerFollowup;
573 }
574
575 CurLoopAttr = BeforeJam;
576 }
577
578 bool HasUserTransforms = false;
579 SmallVector<Metadata *, 4> Properties =
580 createMetadata(Attrs: CurLoopAttr, AdditionalLoopProperties: {}, HasUserTransforms);
581 SmallVector<Metadata *, 4> Args;
582 Args.push_back(Elt: nullptr);
583 Args.append(in_start: Properties.begin(), in_end: Properties.end());
584 LoopID = MDNode::getDistinct(Context&: Ctx, MDs: Args);
585 LoopID->replaceOperandWith(I: 0, New: LoopID);
586
587 TempLoopID->replaceAllUsesWith(MD: LoopID);
588}
589
590void LoopInfoStack::push(BasicBlock *Header, const llvm::DebugLoc &StartLoc,
591 const llvm::DebugLoc &EndLoc) {
592 Active.emplace_back(
593 Args: new LoopInfo(Header, StagedAttrs, StartLoc, EndLoc,
594 Active.empty() ? nullptr : Active.back().get()));
595 // Clear the attributes so nested loops do not inherit them.
596 StagedAttrs.clear();
597}
598
599void LoopInfoStack::push(BasicBlock *Header, clang::ASTContext &Ctx,
600 const clang::CodeGenOptions &CGOpts,
601 ArrayRef<const clang::Attr *> Attrs,
602 const llvm::DebugLoc &StartLoc,
603 const llvm::DebugLoc &EndLoc, bool MustProgress) {
604 // Identify loop hint attributes from Attrs.
605 for (const auto *Attr : Attrs) {
606 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Val: Attr);
607 const OpenCLUnrollHintAttr *OpenCLHint =
608 dyn_cast<OpenCLUnrollHintAttr>(Val: Attr);
609 const HLSLLoopHintAttr *HLSLLoopHint = dyn_cast<HLSLLoopHintAttr>(Val: Attr);
610 // Skip non loop hint attributes
611 if (!LH && !OpenCLHint && !HLSLLoopHint) {
612 continue;
613 }
614
615 LoopHintAttr::OptionType Option = LoopHintAttr::Unroll;
616 LoopHintAttr::LoopHintState State = LoopHintAttr::Disable;
617 unsigned ValueInt = 1;
618 // Translate opencl_unroll_hint attribute argument to
619 // equivalent LoopHintAttr enums.
620 // OpenCL v2.0 s6.11.5:
621 // 0 - enable unroll (no argument).
622 // 1 - disable unroll.
623 // other positive integer n - unroll by n.
624 if (OpenCLHint) {
625 ValueInt = OpenCLHint->getUnrollHint();
626 if (ValueInt == 0) {
627 State = LoopHintAttr::Enable;
628 } else if (ValueInt != 1) {
629 Option = LoopHintAttr::UnrollCount;
630 State = LoopHintAttr::Numeric;
631 }
632 } else if (HLSLLoopHint) {
633 ValueInt = HLSLLoopHint->getDirective();
634 if (HLSLLoopHint->getSemanticSpelling() ==
635 HLSLLoopHintAttr::Spelling::Microsoft_unroll) {
636 if (ValueInt == 0)
637 State = LoopHintAttr::Enable;
638 if (ValueInt > 0) {
639 Option = LoopHintAttr::UnrollCount;
640 State = LoopHintAttr::Numeric;
641 }
642 }
643 } else if (LH) {
644 auto *ValueExpr = LH->getValue();
645 if (ValueExpr) {
646 llvm::APSInt ValueAPS = ValueExpr->EvaluateKnownConstInt(Ctx);
647 ValueInt = ValueAPS.getSExtValue();
648 }
649
650 Option = LH->getOption();
651 State = LH->getState();
652 }
653 switch (State) {
654 case LoopHintAttr::Disable:
655 switch (Option) {
656 case LoopHintAttr::Vectorize:
657 // Disable vectorization by specifying a width of 1.
658 setVectorizeWidth(1);
659 setVectorizeScalable(LoopAttributes::Unspecified);
660 break;
661 case LoopHintAttr::Interleave:
662 // Disable interleaving by speciyfing a count of 1.
663 setInterleaveCount(1);
664 break;
665 case LoopHintAttr::Unroll:
666 setUnrollState(LoopAttributes::Disable);
667 break;
668 case LoopHintAttr::UnrollAndJam:
669 setUnrollAndJamState(LoopAttributes::Disable);
670 break;
671 case LoopHintAttr::VectorizePredicate:
672 setVectorizePredicateState(LoopAttributes::Disable);
673 break;
674 case LoopHintAttr::Distribute:
675 setDistributeState(false);
676 break;
677 case LoopHintAttr::PipelineDisabled:
678 setPipelineDisabled(true);
679 break;
680 case LoopHintAttr::LICMDisabled:
681 setLICMDisabled(true);
682 break;
683 case LoopHintAttr::UnrollCount:
684 case LoopHintAttr::UnrollAndJamCount:
685 case LoopHintAttr::VectorizeWidth:
686 case LoopHintAttr::InterleaveCount:
687 case LoopHintAttr::PipelineInitiationInterval:
688 llvm_unreachable("Options cannot be disabled.");
689 break;
690 }
691 break;
692 case LoopHintAttr::Enable:
693 switch (Option) {
694 case LoopHintAttr::Vectorize:
695 case LoopHintAttr::Interleave:
696 setVectorizeEnable(true);
697 break;
698 case LoopHintAttr::Unroll:
699 setUnrollState(LoopAttributes::Enable);
700 break;
701 case LoopHintAttr::UnrollAndJam:
702 setUnrollAndJamState(LoopAttributes::Enable);
703 break;
704 case LoopHintAttr::VectorizePredicate:
705 setVectorizePredicateState(LoopAttributes::Enable);
706 break;
707 case LoopHintAttr::Distribute:
708 setDistributeState(true);
709 break;
710 case LoopHintAttr::UnrollCount:
711 case LoopHintAttr::UnrollAndJamCount:
712 case LoopHintAttr::VectorizeWidth:
713 case LoopHintAttr::InterleaveCount:
714 case LoopHintAttr::PipelineDisabled:
715 case LoopHintAttr::PipelineInitiationInterval:
716 case LoopHintAttr::LICMDisabled:
717 llvm_unreachable("Options cannot enabled.");
718 break;
719 }
720 break;
721 case LoopHintAttr::AssumeSafety:
722 switch (Option) {
723 case LoopHintAttr::Vectorize:
724 case LoopHintAttr::Interleave:
725 // Apply "llvm.mem.parallel_loop_access" metadata to load/stores.
726 setParallel(true);
727 setVectorizeEnable(true);
728 break;
729 case LoopHintAttr::Unroll:
730 case LoopHintAttr::UnrollAndJam:
731 case LoopHintAttr::VectorizePredicate:
732 case LoopHintAttr::UnrollCount:
733 case LoopHintAttr::UnrollAndJamCount:
734 case LoopHintAttr::VectorizeWidth:
735 case LoopHintAttr::InterleaveCount:
736 case LoopHintAttr::Distribute:
737 case LoopHintAttr::PipelineDisabled:
738 case LoopHintAttr::PipelineInitiationInterval:
739 case LoopHintAttr::LICMDisabled:
740 llvm_unreachable("Options cannot be used to assume mem safety.");
741 break;
742 }
743 break;
744 case LoopHintAttr::Full:
745 switch (Option) {
746 case LoopHintAttr::Unroll:
747 setUnrollState(LoopAttributes::Full);
748 break;
749 case LoopHintAttr::UnrollAndJam:
750 setUnrollAndJamState(LoopAttributes::Full);
751 break;
752 case LoopHintAttr::Vectorize:
753 case LoopHintAttr::Interleave:
754 case LoopHintAttr::UnrollCount:
755 case LoopHintAttr::UnrollAndJamCount:
756 case LoopHintAttr::VectorizeWidth:
757 case LoopHintAttr::InterleaveCount:
758 case LoopHintAttr::Distribute:
759 case LoopHintAttr::PipelineDisabled:
760 case LoopHintAttr::PipelineInitiationInterval:
761 case LoopHintAttr::VectorizePredicate:
762 case LoopHintAttr::LICMDisabled:
763 llvm_unreachable("Options cannot be used with 'full' hint.");
764 break;
765 }
766 break;
767 case LoopHintAttr::FixedWidth:
768 case LoopHintAttr::ScalableWidth:
769 switch (Option) {
770 case LoopHintAttr::VectorizeWidth:
771 setVectorizeScalable(State == LoopHintAttr::ScalableWidth
772 ? LoopAttributes::Enable
773 : LoopAttributes::Disable);
774 if (LH->getValue())
775 setVectorizeWidth(ValueInt);
776 break;
777 default:
778 llvm_unreachable("Options cannot be used with 'scalable' hint.");
779 break;
780 }
781 break;
782 case LoopHintAttr::Numeric:
783 switch (Option) {
784 case LoopHintAttr::InterleaveCount:
785 setInterleaveCount(ValueInt);
786 break;
787 case LoopHintAttr::UnrollCount:
788 setUnrollCount(ValueInt);
789 break;
790 case LoopHintAttr::UnrollAndJamCount:
791 setUnrollAndJamCount(ValueInt);
792 break;
793 case LoopHintAttr::PipelineInitiationInterval:
794 setPipelineInitiationInterval(ValueInt);
795 break;
796 case LoopHintAttr::Unroll:
797 case LoopHintAttr::UnrollAndJam:
798 case LoopHintAttr::VectorizePredicate:
799 case LoopHintAttr::Vectorize:
800 case LoopHintAttr::VectorizeWidth:
801 case LoopHintAttr::Interleave:
802 case LoopHintAttr::Distribute:
803 case LoopHintAttr::PipelineDisabled:
804 case LoopHintAttr::LICMDisabled:
805 llvm_unreachable("Options cannot be assigned a value.");
806 break;
807 }
808 break;
809 }
810 }
811
812 // Identify loop attribute 'code_align' from Attrs.
813 // For attribute code_align:
814 // n - 'llvm.loop.align i32 n' metadata will be emitted.
815 if (const auto *CodeAlign = getSpecificAttr<CodeAlignAttr>(container: Attrs)) {
816 const auto *CE = cast<ConstantExpr>(Val: CodeAlign->getAlignment());
817 llvm::APSInt ArgVal = CE->getResultAsAPSInt();
818 setCodeAlign(ArgVal.getSExtValue());
819 }
820
821 setMustProgress(MustProgress);
822
823 if (CGOpts.OptimizationLevel > 0)
824 // Disable unrolling for the loop, if unrolling is disabled (via
825 // -fno-unroll-loops) and no pragmas override the decision.
826 if (!CGOpts.UnrollLoops &&
827 (StagedAttrs.UnrollEnable == LoopAttributes::Unspecified &&
828 StagedAttrs.UnrollCount == 0))
829 setUnrollState(LoopAttributes::Disable);
830
831 /// Stage the attributes.
832 push(Header, StartLoc, EndLoc);
833}
834
835void LoopInfoStack::pop() {
836 assert(!Active.empty() && "No active loops to pop");
837 Active.back()->finish();
838 Active.pop_back();
839}
840
841void LoopInfoStack::InsertHelper(Instruction *I) const {
842 if (I->mayReadOrWriteMemory()) {
843 SmallVector<Metadata *, 4> AccessGroups;
844 for (const auto &AL : Active) {
845 // Here we assume that every loop that has an access group is parallel.
846 if (MDNode *Group = AL->getAccessGroup())
847 AccessGroups.push_back(Elt: Group);
848 }
849 MDNode *UnionMD = nullptr;
850 if (AccessGroups.size() == 1)
851 UnionMD = cast<MDNode>(Val: AccessGroups[0]);
852 else if (AccessGroups.size() >= 2)
853 UnionMD = MDNode::get(Context&: I->getContext(), MDs: AccessGroups);
854 I->setMetadata(Kind: "llvm.access.group", Node: UnionMD);
855 }
856
857 if (!hasInfo())
858 return;
859
860 const LoopInfo &L = getInfo();
861 if (!L.getLoopID())
862 return;
863
864 if (I->isTerminator()) {
865 for (BasicBlock *Succ : successors(I))
866 if (Succ == L.getHeader()) {
867 I->setMetadata(KindID: llvm::LLVMContext::MD_loop, Node: L.getLoopID());
868 break;
869 }
870 return;
871 }
872}
873